Methods and Inheritance

Add typed methods and extend classes with extends and super.

Syntaxclass Dog extends Animal { }

Class methods are typed functions attached to instances. A class can extend another to inherit its members, calling the parent constructor with super.

Subclasses can add new methods or override existing ones to specialize behavior.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • An Animal base class defines a speak method that is overridden by Dog and Cat subclasses with specific sounds.
  • A Shape base class exposes an area method that Rectangle and Circle override with their own typed calculations.
  • A service class calls super() in a child constructor to pass required fields to the base class before adding its own.

More examples

Typed method with return

Defines two typed methods on a class that operate on private properties set via constructor shorthand.

Example Β· ts
class Rectangle {
  constructor(
    private width: number,
    private height: number,
  ) {}

  area(): number {
    return this.width * this.height;
  }

  perimeter(): number {
    return 2 * (this.width + this.height);
  }
}

Inheritance with super

Extends a base class and overrides a method, calling super() in the child constructor to initialise the base fields.

Example Β· ts
class Animal {
  constructor(public name: string) {}

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

class Dog extends Animal {
  constructor(name: string, public breed: string) {
    super(name);
  }

  speak(): string {
    return `${this.name} barks!`;
  }
}

Method calling super method

Overrides a method and calls super.log() to reuse the parent implementation with additional behaviour.

Example Β· ts
class Logger {
  log(message: string): void {
    console.log(`[LOG] ${message}`);
  }
}

class TimestampLogger extends Logger {
  log(message: string): void {
    super.log(`[${new Date().toISOString()}] ${message}`);
  }
}

Discussion

  • Be the first to comment on this lesson.
Methods and Inheritance β€” TypeScript | SoundsCode