TypeScript language has support for inheritance where a class can inherit from another class.
Typescript uses extends
keyword to implement inheritance.
class Parent {}
class Child extends Parent {}
The class Child
inherits class Parent
. This allows Child
class to inherit all the properties and methods of Parent
class.
Let’s look at inheritance in more detail using a class called Animal
.
class Animal {
weight: number;
height: number;
constructor(weight: number, height: number) {
this.weight = weight;
this.height = height;
}
}
let animal = new Animal(10, 20);
console.log(animal); // Animal {weight: 10, height: 20}
Here we have a simple Animal
class which has weight
and height
as properties.
We will now create a Dog
class that inherits the Animal
class.
class Dog extends Animal {}
Because of the above code, class Dog
inherits all the properties and methods of Animal
class.
let dog = new Dog(11, 22);
console.log(dog); // Dog {weight: 11, height: 22}
As you can see, class Dog does not have any properties of its own but it still gets the properties weight
and height
from the Animal class.
Using super()
The super
keyword is used to call the constructor method of the parent class from the inheriting child class. This is useful when we have a child class that has its own properties and methods but still wants the implementation of the parent class.
For example, let’s say our Dog class needs a legs
property that specifies the number of legs but also wants the weight
and height
from the Animal class, we can use the super()
method to implement the same.
class Animal {
weight: number;
height: number;
constructor(weight: number, height: number) {
this.weight = weight;
this.height = height;
}
}
class Dog extends Animal {
legs: number;
constructor(weight: number, height: number) {
super(weight, height);
this.legs = 4;
}
}
let dog = new Dog(11, 22);
console.log(dog); // Dog {weight: 11, height: 22, legs: 4}
As you see, when declaring a constructor function inside the Dog class, we make use of the super()
method which takes two arguments weight
and height
. This method basically calls the constructor method of the Animal
class and assigns the properties. You can also see, we have a legs
property that belongs to the Dog class which gets assigned inside the constructor of the Dog class.
Just like properties, we can also access methods of the parent class.
class Animal {
weight: number;
height: number;
constructor(weight: number, height: number) {
this.weight = weight;
this.height = height;
}
kingdom() {
console.log("I belong to Animal Kingdom");
}
}
class Dog extends Animal {
legs: number;
constructor(weight: number, height: number) {
super(weight, height);
this.legs = 4;
}
}
let dog = new Dog(11, 22);
dog.kingdom(); // I belong to Animal Kingdom
In this example, we have a kingdom()
method defined inside the Animal class. As you can see, the dog
object has access to the kingdom()
method of the parent class.