Skip to content
Home Tutorials Roadmaps Courses
Log in Join free
Tutorials TypeScript Inheritance
TypeScript Intermediate FREE

Inheritance

Lesson 2 of 17 Intermediate Interactive

Classes can extend other classes to inherit properties and methods.

Syntax

TYPESCRIPT
class Cat extends Animal {
    speak(): string {
        return `${this.name} meows`;
    }
}
Class Inheritance
TYPESCRIPT
class Shape {
    constructor(public color: string) {}

    area(): number {
        return 0;
    }
}

class Circle extends Shape {
    constructor(color: string, public radius: number) {
        super(color);
    }

    area(): number {
        return Math.PI * this.radius ** 2;
    }
}

class Rectangle extends Shape {
    constructor(color: string, public w: number, public h: number) {
        super(color);
    }

    area(): number {
        return this.w * this.h;
    }
}

let c = new Circle("red", 5);
console.log(`${c.color} circle: ${c.area().toFixed(2)}`);

let r = new Rectangle("blue", 4, 6);
console.log(`${r.color} rect: ${r.area()}`);

Practice

1
Exercise

Practice this concept.

Answer
Write the code as shown above.

Quick Quiz

1

What did you learn?

This covers the basics.

Interview Questions

It is a fundamental TypeScript feature.