- TypeScript Tutorial
- TypeScript Home
- TypeScript Introduction
- TypeScript Setup
- TypeScript First Program
- TypeScript vs JavaScript
- TypeScript Data Types
- TypeScript Type Inference
- TypeScript Type Annotations
- TypeScript Interfaces
- TypeScript Enums
- TypeScript Type Aliases
- TypeScript Type Assertions
- TypeScript Variables
- TypeScript Functions
- TypeScript Functions
- TypeScript Optional Parameters
- TypeScript Default Parameters
- TypeScript Rest Parameters
- TypeScript Arrow Functions
- Classes and Objects
- Introduction to Classes
- Properties and Methods
- Access Modifiers
- Static Members
- Inheritance
- Abstract Classes
- Interfaces vs Classes
- Advanced Types
- TypeScript Union Types
- TypeScript Intersection Types
- TypeScript Literal Types
- TypeScript Nullable Types
- TypeScript Type Guards
- TypeScript Discriminated Unions
- TypeScript Index Signatures
- TypeScript Generics
- Introduction to Generics
- TypeScript Generic Functions
- TypeScript Generic Classes
- TypeScript Generic Constraints
- TypeScript Modules
- Introduction to Modules
- TypeScript Import and Export
- TypeScript Default Exports
- TypeScript Namespace
- Decorators
- Introduction to Decorators
- TypeScript Class Decorators
- TypeScript Method Decorators
- TypeScript Property Decorators
- TypeScript Parameter Decorators
- Configuration
- TypeScript tsconfig.json File
- TypeScript Compiler Options
- TypeScript Strict Mode
- TypeScript Watch Mode
Introduction to Classes in TypeScript
Classes in TypeScript are a blueprint for creating objects with specific properties and methods. TypeScript introduces static typing to JavaScript classes, enabling better tooling, type safety, and enhanced development experience. Classes allow the creation of reusable code components and are central to object-oriented programming (OOP) principles.
Creating a Basic Class
In TypeScript, classes are defined using the class keyword, and can contain properties and methods. Here's how a simple class is created:
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
greet(): string {
return `Hello, my name is ${this.name} and I am ${this.age} years old.`;
}
}
const person1 = new Person("Alice", 30);
console.log(person1.greet()); // Output: Hello, my name is Alice and I am 30 years old.
In this example:
Personis a class with propertiesnameandage.- The
constructoris used to initialize these properties when a new instance of the class is created. - The
greetmethod returns a greeting message.
Class Constructor
The constructor is a special method used to initialize a class object. It is called automatically when a new instance of the class is created using the new keyword.
class Car {
make: string;
model: string;
constructor(make: string, model: string) {
this.make = make;
this.model = model;
}
getDetails(): string {
return `${this.make} ${this.model}`;
}
}
const myCar = new Car("Toyota", "Corolla");
console.log(myCar.getDetails()); // Output: Toyota Corolla
Access Modifiers
TypeScript supports three types of access modifiers for class properties and methods:
public: Accessible from anywhere (default modifier).private: Accessible only within the class.protected: Accessible within the class and subclasses.
class Employee {
private id: number;
public name: string;
protected position: string;
constructor(id: number, name: string, position: string) {
this.id = id;
this.name = name;
this.position = position;
}
getEmployeeDetails(): string {
return `ID: ${this.id}, Name: ${this.name}, Position: ${this.position}`;
}
}
const emp = new Employee(1, "John", "Manager");
console.log(emp.getEmployeeDetails()); // Output: ID: 1, Name: John, Position: Manager
// console.log(emp.id); // Error: Property 'id' is private and only accessible within class 'Employee'.
In this example:
idisprivate, so it cannot be accessed directly outside the class.nameispublic, so it can be accessed freely.positionisprotected, meaning it can be accessed within the class and subclasses.
Inheritance in Classes
TypeScript supports inheritance, allowing a class to extend another class and inherit its properties and methods. The extends keyword is used for inheritance.
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
makeSound(): string {
return `${this.name} makes a sound.`;
}
}
class Dog extends Animal {
breed: string;
constructor(name: string, breed: string) {
super(name); // Call the parent class constructor
this.breed = breed;
}
makeSound(): string {
return `${this.name} barks.`;
}
}
const dog = new Dog("Buddy", "Golden Retriever");
console.log(dog.makeSound()); // Output: Buddy barks.
Here:
- The
Dogclass extends theAnimalclass, inheriting its properties and methods. - The
superkeyword calls the parent class's constructor.
Getters and Setters
Getters and setters allow you to define methods to access and modify private properties. They provide more control over how properties are accessed or updated.
class BankAccount {
private balance: number;
constructor(initialBalance: number) {
this.balance = initialBalance;
}
get accountBalance(): number {
return this.balance;
}
set deposit(amount: number) {
if (amount > 0) {
this.balance += amount;
}
}
}
const account = new BankAccount(1000);
console.log(account.accountBalance); // Output: 1000
account.deposit = 500; // Using the setter to add money
console.log(account.accountBalance); // Output: 1500
In this example:
- The
accountBalancegetter allows us to access thebalanceproperty. - The
depositsetter allows us to modify thebalanceproperty with a validation check.
Static Methods and Properties
Static methods and properties are associated with the class itself, rather than instances of the class. They are useful for functionality that doesn’t depend on instance-specific data.
class MathUtils {
static add(a: number, b: number): number {
return a + b;
}
}
console.log(MathUtils.add(5, 3)); // Output: 8
In this example:
- The
addmethod isstatic, so it is called on the classMathUtilsdirectly, not on an instance.
Summary
Classes in TypeScript allow you to define objects with properties and methods, providing a blueprint for creating instances. They support key OOP features like inheritance, access modifiers (public, private, protected), and static members. TypeScript enhances class usage with static typing, making it easier to build and maintain complex applications.