Inheritance is a fundamental concept in object-oriented programming that TypeScript fully supports. It allows a class to inherit properties and methods from another class, promoting code reuse and establishing a hierarchical relationship between classes.
In TypeScript, you can create a derived class using the extends
keyword. Here's a simple example:
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
move(distance: number = 0) {
console.log(`${this.name} moved ${distance}m.`);
}
}
class Dog extends Animal {
bark() {
console.log('Woof! Woof!');
}
}
In this example, Dog
is a derived class that inherits from the Animal
base class. The Dog
class automatically gains the name
property and move
method from Animal
.
Derived classes can override methods from the base class to provide specialized behavior. TypeScript uses the super
keyword to call the base class constructor or methods.
class Snake extends Animal {
constructor(name: string) {
super(name);
}
move(distance: number = 5) {
console.log("Slithering...");
super.move(distance);
}
}
In this example, the Snake
class overrides the move
method but still calls the base class implementation using super.move()
.
TypeScript supports various access modifiers that affect how properties and methods are inherited:
public
: Accessible from anywhere (default)protected
: Accessible within the class and its subclassesprivate
: Accessible only within the declaring classprotected
modifier for properties and methods that should be accessible to subclasses but not to the public.TypeScript also supports more advanced inheritance concepts, such as:
Understanding these concepts will help you leverage the full power of inheritance in TypeScript and create more maintainable, scalable code.
Inheritance is a powerful feature in TypeScript that enables developers to create hierarchical relationships between classes. By mastering inheritance, you can write more efficient and organized code, taking full advantage of object-oriented programming principles in your TypeScript projects.