Inheritance and Interfaces
Inheritance and Interfaces in TypeScript
TypeScript supports classical OOP inheritance through extends and structural typing through implements.
extends (class inheritance)
A subclass inherits all public and protected members. Call super() in the constructor before accessing this.
implements (interface conformance)
A class can implement one or more interfaces. TypeScript verifies that all required members exist with compatible types.
Abstract classes
Marked with abstract, these classes cannot be instantiated directly. They may contain abstract methods (no body) that subclasses must implement.
Method overriding
Override a parent method by declaring a method with the same name in the subclass. Add override (TS 4.3+) to catch typos and ensure the method actually exists in the parent.
Key points:
- A class can
extendonly one class butimplementmany interfaces. - Abstract classes can have both implemented and abstract members.
- The
overridekeyword is optional but recommended for clarity and safety.
Code Examples
class Animal {
constructor(protected name: string) {}
speak(): string {
return `${this.name} makes a sound.`;
}
}
class Dog extends Animal {
constructor(name: string, private breed: string) {
super(name);
}
override speak(): string {
return `${this.name} barks!`;
}
info(): string {
return `${this.name} is a ${this.breed}`;
}
}
const d = new Dog("Rex", "Labrador");
console.log(d.speak());
console.log(d.info());super() forwards arguments to the parent constructor. The override keyword documents intent and catches typos.
interface Serializable {
serialize(): string;
}
abstract class Shape implements Serializable {
abstract area(): number;
serialize(): string {
return JSON.stringify({ type: this.constructor.name, area: this.area() });
}
}
class Circle extends Shape {
constructor(private radius: number) { super(); }
area(): number { return Math.PI * this.radius ** 2; }
}
class Rectangle extends Shape {
constructor(private w: number, private h: number) { super(); }
area(): number { return this.w * this.h; }
}
const shapes: Shape[] = [new Circle(5), new Rectangle(4, 6)];
shapes.forEach(s => console.log(s.serialize()));Abstract classes define a template: concrete subclasses provide the area() implementation while inheriting serialize() for free.
Quick Quiz
1. Can you instantiate an abstract class directly?
2. How many classes can a TypeScript class extend?
Was this lesson helpful?