Inheritance in TypeScript allows you to create a new class based on an existing class. This is useful for creating a hierarchy of classes that share common characteristics while allowing for specific variations. TypeScript uses the extends
keyword to establish inheritance.
Here’s an overview of how inheritance works in TypeScript, along with some examples:
Basic Inheritance
You define a base class and a derived class that extends the base class:
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
move(distance: number = 0) {
console.log(`${this.name} moved ${distance} meters.`);
}
}
class Dog extends Animal {
bark() {
console.log('Woof! Woof!');
}
}
const dog = new Dog('Tiger');
dog.bark(); // Output: Woof! Woof!
dog.move(10); // Output: Rex moved 10 meters.
In this example:
Animal
is the base class.Dog
is the derived class that extendsAnimal
.- The
Dog
class inherits thename
property and themove
method from theAnimal
class.
Overriding Methods
A derived class can override methods from the base class:
class Bird extends Animal {
move(distance: number = 0) {
console.log(`${this.name} flew ${distance} meters.`);
}
}
const bird = new Bird('crow');
bird.move(10); // Output: crow flew 10 meters.
Here, the move
method in the Bird
class overrides the move
method in the Animal
class.
Using super
You can call methods from the base class using the super
keyword:
class Snake extends Animal {
constructor(name: string) {
super(name); // Call the base class constructor
}
move(distance: number = 5) {
console.log('Slithering...');
super.move(distance); // Call the base class method
}
}
const snake = new Snake('Slither');
snake.move(); // Output: Slithering... Slither moved 5 meters.
In this example:
- The
Snake
class calls the constructor of theAnimal
class usingsuper(name)
. - The
move
method in theSnake
class calls themove
method of theAnimal
class usingsuper.move(distance)
.