DevAcademy
IntermediateTypeScript

Classes

Learn how TypeScript adds typed properties, constructors, and inheritance to JavaScript classes.

Reading Time

18 min

Lesson

Lesson 16 of 30

Typed Class Properties

TypeScript classes declare their properties with types up front, and the constructor is responsible for initializing them.

A Basic Typed Class

class User {
  name: string;
  email: string;

  constructor(name: string, email: string) {
    this.name = name;
    this.email = email;
  }

  greet(): string {
    return `Hello, ${this.name}!`;
  }
}

const user = new User("Alice", "alice@example.com");

Constructor Parameter Properties

TypeScript offers a shorthand that declares and initializes a property directly from a constructor parameter, removing repetitive boilerplate.

Parameter Properties Shorthand

class User {
  constructor(
    public name: string,
    public email: string,
  ) {}
}

// Equivalent to manually declaring name/email and assigning them in the body

Inheritance

A class extends another with extends, inheriting its members. The subclass constructor must call super() before accessing this if the parent has its own constructor.

Class Inheritance

class Animal {
  constructor(public name: string) {}

  speak(): string {
    return `${this.name} makes a sound.`;
  }
}

class Dog extends Animal {
  speak(): string {
    return `${this.name} barks.`;
  }
}

const pet: Animal = new Dog("Rex");
console.log(pet.speak()); // "Rex barks."

Abstract Classes

An abstract class can’t be instantiated directly — it exists to be extended, and can declare abstract methods that subclasses are required to implement.

Abstract Class

abstract class Shape {
  abstract area(): number;

  describe(): string {
    return `Area: ${this.area()}`;
  }
}

class Square extends Shape {
  constructor(private side: number) {
    super();
  }

  area(): number {
    return this.side ** 2;
  }
}

new Shape(); // Error: Cannot create an instance of an abstract class

Classes Implement, Interfaces Extend

A class uses implements to satisfy an interface’s shape, while an interface uses extends to build on another interface — both describe the same idea of "has this shape," but with slightly different keywords depending on context.

Best Practice

Use the constructor parameter property shorthand for simple classes — it keeps declarations concise and puts each property’s type right next to where it’s assigned.

Interview Questions

Quick Quiz

1. What does the parameter property shorthand (constructor(public name: string)) do?

2. What must a subclass constructor call before using this, if the parent has its own constructor?

3. Can an abstract class be instantiated directly with new?