You are here: Home / Topics / Inheritance in TypeScript

Inheritance in TypeScript

Filed under: TypeScript on 2024-03-18 11:36:27

Inheritance is a mechanism that allows a class to inherit properties and methods from another class. It enables code reuse and promotes the concept of a hierarchical relationship between classes. TypeScript supports single inheritance, meaning a class can only inherit from a single base class. To implement inheritance in TypeScript, you can use the extends keyword.

Example 1:


index.ts:
class Animal {
protected name: string;
constructor(name: string) {
    this.name = name;
}
    eat(): void {
    console.log(`${this.name} is eating.`);
    }
}
class Cat extends Animal {
    meow(): void {
    console.log(`${this.name} says meow.`);
}
}
// Create an instance of the Cat class
const cat = new Cat("Cat1");
cat.eat(); // Output: Cat1 is eating.
cat.meow(); // Output: Cat1 says meow.


Example 2:


index.ts:
class A {
    constructor() {
    console.log("A class");
    }
}
class B extends A {
    constructor() {

    super();
    console.log("B class");
    }
}
new B();


Example 3:


index.ts:
class Person {
    name: string;
    age: number;
constructor(name, age) {
    this.name = name;
    this.age = age;
    console.log("Person: " + name + " " + age);
}
}
class Employee extends Person {
    salary: number;
    department: string;
    constructor(name, age, salary, department) {
    super(name, age);
    this.salary = salary;
    this.department = department;
}
    disp = () => {
    console.log(`Name: ${this.name}, age: ${this.age}, salary: ${this.salary}, department${this.department}`);
}
}
new Employee('Shyam', 25, 25000, 'Sales').disp();

About Author:
J
Java Developer     View Profile
Hi, I am using MCQ Buddy. I love to share content on this website.