Javascript Decorators

A decorator starts with an @ symbol and can be put in front of classes and class member variable and methods.

It doesn't seems to be able to used on free functions yet. There seems to be some controversies

Under the hood, a decorator is a function takes a decorated value and a context. A decorator can do four things

  1. Change the decorated entity by mutating value
  2. Replace the decorated entity by returning a compatible value
  3. Exposing access to the decorated entity to others (via context.access)
  4. Processing the decorated entity and its container (if it has one), after both exist: That functionality is provided by context.addInitializer.

The context parameter contains some additional information. We can see it in Decorator’s TypeScript type.

Types In TypeScript

Typescript provides types such as ClassMethodDecoratorContext which we can help to write decorators.

Class Method Decorators

Example: mimic bound method in JavaScript

See also

References


parent: JavaScript, TypeScript tags:typescriptjavascript