0
0
Typescriptprogramming~5 mins

Why inheritance needs types in Typescript

Choose your learning style9 modes available
Introduction

Inheritance helps us create new things based on old ones. Types make sure these new things behave correctly and safely.

When you want to build a new class that shares features with an existing class.
When you want to make sure the new class follows the rules of the old class.
When you want to catch mistakes early by checking types before running the program.
Syntax
Typescript
class Parent {
  property: string;
  constructor(property: string) {
    this.property = property;
  }
}

class Child extends Parent {
  extraProperty: number;
  constructor(property: string, extraProperty: number) {
    super(property);
    this.extraProperty = extraProperty;
  }
}

extends keyword means Child inherits from Parent.

TypeScript checks that Child matches Parent's type rules.

Examples
Dog inherits name from Animal and adds breed.
Typescript
class Animal {
  name: string;
  constructor(name: string) {
    this.name = name;
  }
}

class Dog extends Animal {
  breed: string;
  constructor(name: string, breed: string) {
    super(name);
    this.breed = breed;
  }
}
Car inherits wheels from Vehicle and adds brand.
Typescript
class Vehicle {
  wheels: number;
  constructor(wheels: number) {
    this.wheels = wheels;
  }
}

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

This program shows a Student inheriting from Person. Types make sure Student has a name and studentId. The greet method uses both.

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

class Student extends Person {
  studentId: number;
  constructor(name: string, studentId: number) {
    super(name);
    this.studentId = studentId;
  }
  greet() {
    return `${super.greet()} and my student ID is ${this.studentId}`;
  }
}

const student = new Student("Alice", 12345);
console.log(student.greet());
OutputSuccess
Important Notes

Types help catch errors like missing properties or wrong data types before running the code.

Inheritance with types makes your code easier to understand and maintain.

Summary

Inheritance lets one class reuse code from another.

Types ensure the new class follows the rules of the original class.

This helps prevent mistakes and makes code safer.