DEV Community

Mahabubur Rahman
Mahabubur Rahman

Posted on

Inheritance Typescript

Create a Parent Class

class Parent {
    name: string;
    age: number;
    address: string;

    constructor(name: string, age: number, address: string) {
        this.name = name;
        this.age = age;
        this.address = address;
    }

    makeSleep(hours: number): string {
        return `This ${this.name} will sleep for ${hours}`;
    }
}
Enter fullscreen mode Exit fullscreen mode

After Create a Child Classes for Send Parent Class Data

class Student extends Parent {
    constructor(name: string, age: number, address: string) {
        super(name, age, address);
    }
}
Enter fullscreen mode Exit fullscreen mode
const student1 = new Student("Mr x", 20, "New York");
student1.age;
Enter fullscreen mode Exit fullscreen mode

Another Example

class Teacher extends Parent {
    designation: string;

    constructor(name: string, age: number, address: string, designation: string) {
        super(name, age, address);
        this.designation = designation;
    }

    takeClasses(numOfClass: number): string {
        return `this ${this.name} will take ${numOfClass}`; // Different
    }
}
Enter fullscreen mode Exit fullscreen mode
const teacher1 = new Teacher("Mr Y", 54, "UK", "Professor");
teacher1.designation;
Enter fullscreen mode Exit fullscreen mode

Top comments (0)