create a subclass with a constructor in typescript

To create a subclass with a constructor in TypeScript, you can use the super() method inside the constructor of the child class. The super() method refers to the parent class constructor and must be called before accessing any property of the parent class.

Here's an example:

index.ts
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;
    }
}

const myDog = new Dog('Fido', 'Labrador');
console.log(myDog.name); // Output: Fido
console.log(myDog.breed); // Output: Labrador
381 chars
19 lines

In this example, we have a parent class Animal with a constructor that takes a name parameter. The child class Dog extends the Animal class and has an additional property called breed. The Dog class also has a constructor that takes both name and breed parameters. We call super(name) inside the Dog constructor to call the parent constructor and pass the name parameter. Finally, we set the breed property of the Dog class to the breed parameter.

When we create an instance of the Dog class and log its properties to the console, we can see that the name and breed properties are set correctly.

gistlibby LogSnag