Decorators enable us to extend a class or object by adding behaviors without modifying the code. Decorators wrap the class with extra functionality. They can be attached to a class, property, method, parameter, and accessor. In ECMAScript 2016, decorators are proposed to modify the behavior of a class. Decorators are prefixed with the @
symbol and a decorator name that resolves to a function called at runtime
.
The following code snippet shows the authorize function, and it can be used as the @authorize
decorator on any other class:
function authorize(target) { // check the authorization of the use to access the "target" }
Class decorators are declared before the class declaration. Class decorators can observe, modify, and replace the definition of a class by applying to the constructor of that class. The signature of ClassDecorator
in TypeScript is as illustrated:
declare type ClassDecorator = <TFunction extends Function>(target: TFunction) => TFunction...