Member-only story
Learning TypeScript 05 — Decorators
This feature is present in other languages as Attributes, Attribute Decorations or Decorators, and are going to be present in future EcmaScript versions.
Some years ago we used a similar pattern called Mixin but these two patterns have some differences. When you use a mixin you’re literally extending your class. A common example that we did in the past hundreds of times is to add a mixin to make your class be able to emit events.
But when you use a decorator, what you are doing is to encapsulate some functionality, without extending your class, and respecting the same structure that you have (example: implementing the same interface).
We have basically two types of decorators.
- We can decorate a class: Decorating a class we are going to implement the changes to the whole class, receiving the constructor and modifying all that we want.
Imagine that we have a class that is called MyHero, and has two properties, name and strength, if we decorate the class as Archer we will obtain something like this:
And if we change from Archer to Wizard: