...

/

Inheritance and Decorators in TypeScript

Inheritance and Decorators in TypeScript

Learn about class inheritance and different types of decorators in TypeScript.

Just like an interface can define a class, it can also extend the members and functionality of other classes. We can make a class inherit from another by appending the extends keyword to the class name, including the name of the class we want to inherit its members from:

Press + to interact
class Car {
make: string;
constructor(make: string) {
this.make = make;
}
}
class Sedan extends Car {
model: string;
constructor(make: string, model: string) {
super(make);
this.model = model;
}
}
const myCar = new Sedan('2022', 'BMW');
console.log(myCar);

In the preceding class, we extend from a parent Car class on line 9, which already exposes a member called make. We can populate the members by the parent class and execute their constructor using the super method on line 13, which points to the parent constructor. We can also override methods from the parent class by appending a method with the same name. Nevertheless, we can still execute the original parent’s class methods as it is still accessible from the super object.

Classes and interfaces are basic features of the TypeScript language. As we will see in the following section, decorators enhance the use of classes in an application by extending them with custom functionality.

Decorators

Decorators allow us to add metadata to class declarations for further use. By creating decorators, we are defining special annotations that may impact how our classes, methods, or functions behave or simply altering the data we define in fields or parameters. They are a powerful way to augment our type’s native functionalities without creating subclasses or inheriting from other types. It is, by far, one of the most exciting features ...