TypeScript Classes

TypeScript brings the power of object-oriented programming to JavaScript by adding strong typing to classes. Classes help you organize code in a structured way, making it easier to reuse and maintain. Whether you're building small scripts or large applications, understanding TypeScript classes will help you write cleaner and more reliable code.

Defining Classes in TypeScript

A class in TypeScript is a blueprint for creating objects with predefined properties and methods. Unlike plain JavaScript, TypeScript allows you to specify types for class members, ensuring better code safety.

Here’s a basic example of a class in TypeScript:

typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
          class Car {
  brand: string;
  year: number;

  constructor(brand: string, year: number) {
    this.brand = brand;
    this.year = year;
  }

  displayInfo() {
    console.log(`This is a ${this.brand} car from ${this.year}.`);
  }
}

const myCar = new Car("Toyota", 2020);
myCar.displayInfo(); // Output: "This is a Toyota car from 2020."
        

In this example:

  • brand and year are properties with explicit types.
  • The constructor method initializes these properties when a new Car is created.
  • displayInfo() is a method that logs details about the car.

Constructor Methods and Properties

The constructor is a special method that runs when you create a new instance of a class. It’s where you set up initial values for properties. TypeScript also provides shortcuts to reduce boilerplate code.

Shorthand Property Initialization

Instead of manually assigning properties in the constructor, you can declare them directly in the parameters:

typescript
1
2
3
4
5
6
          class Person {
  constructor(public name: string, public age: number) {}
}

const user = new Person("Alice", 30);
console.log(user.name); // "Alice"
        

The public keyword automatically assigns the parameters as class properties.

Readonly and Private Properties

TypeScript allows access modifiers to control property visibility:

  • readonly prevents modification after initialization.
  • private restricts access to within the class.
typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
          class Account {
  readonly id: string;
  private balance: number;

  constructor(id: string, balance: number) {
    this.id = id;
    this.balance = balance;
  }

  getBalance() {
    return this.balance;
  }
}

const myAccount = new Account("12345", 1000);
console.log(myAccount.getBalance()); // 1000
// myAccount.balance = 2000; // Error: Property 'balance' is private
        

Inheritance in TypeScript Classes

Inheritance allows one class to inherit properties and methods from another, promoting code reuse. TypeScript uses the extends keyword for this.

Basic Inheritance

A child class can extend a parent class, gaining all its features while adding new ones:

typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
          class Animal {
  constructor(public name: string) {}

  move(distance: number = 0) {
    console.log(`${this.name} moved ${distance} meters.`);
  }
}

class Dog extends Animal {
  bark() {
    console.log("Woof! Woof!");
  }
}

const myDog = new Dog("Buddy");
myDog.move(10); // "Buddy moved 10 meters."
myDog.bark();   // "Woof! Woof!"
        

Overriding Methods

A child class can override a parent’s method while still accessing the original using super:

typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
          class Cat extends Animal {
  constructor(name: string, public color: string) {
    super(name);
  }

  move(distance = 5) {
    console.log(`${this.name} (a ${this.color} cat) sneaks...`);
    super.move(distance);
  }
}

const myCat = new Cat("Whiskers", "black");
myCat.move(); // "Whiskers (a black cat) sneaks..." then "Whiskers moved 5 meters."
        

Abstract Classes

For advanced use cases, TypeScript supports abstract classes—base classes that can’t be instantiated directly but must be extended:

typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
          abstract class Shape {
  abstract getArea(): number;

  displayArea() {
    console.log(`Area: ${this.getArea()}`);
  }
}

class Circle extends Shape {
  constructor(private radius: number) {
    super();
  }

  getArea() {
    return Math.PI * this.radius ** 2;
  }
}

const myCircle = new Circle(5);
myCircle.displayArea(); // "Area: 78.53981633974483"
        

Key Takeaways

  • Classes in TypeScript provide structure and type safety.
  • Constructors initialize objects, with shortcuts for cleaner code.
  • Inheritance (extends) and method overriding (super) enable reusable hierarchies.
  • Access modifiers (public, private, readonly) control property visibility.
  • Abstract classes define templates for other classes to implement.

Using these features, you can build well-organized and maintainable applications in TypeScript.