Is the Typescript @Component "Decorator" related to the decorator pattern?

1k Views Asked by At

The @Component({}) line in a component .ts file is referred to as a Decorator. Is this in relation to the Decorator Pattern, or are they unrelated?

2

There are 2 best solutions below

0
On BEST ANSWER

Typescript decorator:

It’s compile time. It’s one time but permanent change, as the class that get decorated is different from the original class. And it's simple, basically just a function.

The common scenario is one decorator apply on different classes. For example: in Angular , the @injector decorator apply on various classes and make them injectable.

For the general decorator pattern:

The common scenario is different decorators on one single class. It’s pretty heavy-lifting. You need to create decorator class, common parent class for decorator class and original class, and different child decorator classes. The original class remains unchanged and you can apply decorator as see fit during run time.

Example: you have a coffee class. You can create different decorator classes: Espresso , Cappuccino, even expresso + Cappuccino coffee if you want.

Just my 2 cents.

0
On

They are related, since you decorate an existing class with additional functionality. They are not the same, because the typescript @Decorator is applied at compile time, while the decorator pattern can also be used to decorate a class at runtime, for example:

let armoredenemy = new Armored(new Enemy())
let enemy = new Enemy()

While the program is running, you can still decide if you want to decorate a class or not.