0
0
Typescriptprogramming~5 mins

Extending classes with types in Typescript

Choose your learning style9 modes available
Introduction

Extending classes with types helps you create new classes based on existing ones. This saves time and keeps your code organized.

When you want a new class to have all features of an existing class plus some new ones.
When you want to reuse code from a base class without rewriting it.
When you want to create a family of related classes with shared behavior.
When you want to add specific properties or methods to a general class.
When you want to keep your code easy to maintain and understand.
Syntax
Typescript
class ChildClass extends ParentClass {
  // new properties or methods
}

The extends keyword means the new class gets all features of the parent class.

You can add new properties or methods inside the child class.

Examples
This example shows a class Dog that extends Animal. It changes the speak method.
Typescript
class Animal {
  name: string;
  constructor(name: string) {
    this.name = name;
  }
  speak() {
    console.log(`${this.name} makes a sound.`);
  }
}

class Dog extends Animal {
  speak() {
    console.log(`${this.name} barks.`);
  }
}
Here, Car extends Vehicle. It uses super to call the parent constructor and adds a new property.
Typescript
class Vehicle {
  wheels: number;
  constructor(wheels: number) {
    this.wheels = wheels;
  }
}

class Car extends Vehicle {
  brand: string;
  constructor(brand: string) {
    super(4);
    this.brand = brand;
  }
}
Sample Program

This program creates a Person class and a Student class that extends it. The student can greet and study.

Typescript
class Person {
  name: string;
  constructor(name: string) {
    this.name = name;
  }
  greet() {
    console.log(`Hello, my name is ${this.name}.`);
  }
}

class Student extends Person {
  grade: number;
  constructor(name: string, grade: number) {
    super(name);
    this.grade = grade;
  }
  study() {
    console.log(`${this.name} is studying for grade ${this.grade}.`);
  }
}

const student = new Student("Alice", 10);
student.greet();
student.study();
OutputSuccess
Important Notes

Use super() in the child class constructor to call the parent class constructor.

Child classes inherit all public and protected members from the parent class.

You can override methods in the child class to change behavior.

Summary

Extending classes lets you build new classes from existing ones.

Use extends to inherit properties and methods.

Call super() to run the parent constructor inside the child.