Introduction

To enable experimental support for decorators, you must enable the compiler option either on the command line or in your tsconfig.json:

Command Line:

tsconfig.json:

  1. {
  2. "compilerOptions": {
  3. "target": "ES5",
  4. "experimentalDecorators": true
  5. }
  6. }

Decorators

A Decorator is a special kind of declaration that can be attached to a , method, , property, or .Decorators use the form @expression, where expression must evaluate to a function that will be called at runtime with information about the decorated declaration.

For example, given the decorator @sealed we might write the sealed function as follows:

  1. function sealed(target) {
  2. // do something with 'target' ...
  3. }

NOTE  You can see a more detailed example of a decorator in Class Decorators, below.

If we want to customize how a decorator is applied to a declaration, we can write a decorator factory.A Decorator Factory is simply a function that returns the expression that will be called by the decorator at runtime.

We can write a decorator factory in the following fashion:

  1. function color(value: string) { // this is the decorator factory
  2. return function (target) { // this is the decorator
  3. // do something with 'target' and 'value'...
  4. }
  5. }

NOTE  You can see a more detailed example of a decorator factory in , below.

Decorator Composition

Multiple decorators can be applied to a declaration, as in the following examples:

  • On a single line:
  1. @f @g x
  • On multiple lines:
  1. @f
  2. @g
  3. x

When multiple decorators apply to a single declaration, their evaluation is similar to . In this model, when composing functions f and g, the resulting composite (fg)(x) is equivalent to f(g(x)).

As such, the following steps are performed when evaluating multiple decorators on a single declaration in TypeScript:

  • The expressions for each decorator are evaluated top-to-bottom.
  • The results are then called as functions from bottom-to-top.If we were to use decorator factories, we can observe this evaluation order with the following example:
  1. function f() {
  2. console.log("f(): evaluated");
  3. return function (target, propertyKey: string, descriptor: PropertyDescriptor) {
  4. console.log("f(): called");
  5. }
  6. }
  7. function g() {
  8. console.log("g(): evaluated");
  9. return function (target, propertyKey: string, descriptor: PropertyDescriptor) {
  10. console.log("g(): called");
  11. }
  12. }
  13. class C {
  14. @f()
  15. @g()
  16. method() {}
  17. }

Which would print this output to the console:

  1. f(): evaluated
  2. g(): evaluated
  3. g(): called
  4. f(): called

Decorator Evaluation

There is a well defined order to how decorators applied to various declarations inside of a class are applied:

  • Parameter Decorators, followed by Method, Accessor, or Property Decorators are applied for each instance member.
  • Parameter Decorators, followed by Method, Accessor, or Property Decorators are applied for each static member.
  • Parameter Decorators are applied for the constructor.
  • Class Decorators are applied for the class.

A Class Decorator is declared just before a class declaration.The class decorator is applied to the constructor of the class and can be used to observe, modify, or replace a class definition.A class decorator cannot be used in a declaration file, or in any other ambient context (such as on a declare class).

The expression for the class decorator will be called as a function at runtime, with the constructor of the decorated class as its only argument.

If the class decorator returns a value, it will replace the class declaration with the provided constructor function.

NOTE Should you choose to return a new constructor function, you must take care to maintain the original prototype.The logic that applies decorators at runtime will not do this for you.

The following is an example of a class decorator (@sealed) applied to the Greeter class:

  1. function sealed(constructor: Function) {
  2. Object.seal(constructor);
  3. Object.seal(constructor.prototype);
  4. }

When @sealed is executed, it will seal both the constructor and its prototype.

Next we have an example of how to override the constructor.

  1. function classDecorator<T extends {new(...args:any[]):{}}>(constructor:T) {
  2. return class extends constructor {
  3. newProperty = "new property";
  4. hello = "override";
  5. }
  6. }
  7. @classDecorator
  8. class Greeter {
  9. property = "property";
  10. hello: string;
  11. constructor(m: string) {
  12. }
  13. }
  14. console.log(new Greeter("world"));

Method Decorators

A Method Decorator is declared just before a method declaration.The decorator is applied to the Property Descriptor for the method, and can be used to observe, modify, or replace a method definition.A method decorator cannot be used in a declaration file, on an overload, or in any other ambient context (such as in a declare class).

The expression for the method decorator will be called as a function at runtime, with the following three arguments:

  • Either the constructor function of the class for a static member, or the prototype of the class for an instance member.
  • The name of the member.
  • The Property Descriptor for the member.

If the method decorator returns a value, it will be used as the Property Descriptor for the method.

NOTE  The return value is ignored if your script target is less than ES5.

The following is an example of a method decorator (@enumerable) applied to a method on the Greeter class:

  1. class Greeter {
  2. greeting: string;
  3. constructor(message: string) {
  4. this.greeting = message;
  5. }
  6. greet() {
  7. return "Hello, " + this.greeting;
  8. }
  9. }

We can define the @enumerable decorator using the following function declaration:

  1. function enumerable(value: boolean) {
  2. return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
  3. descriptor.enumerable = value;
  4. };
  5. }

The @enumerable(false) decorator here is a .When the @enumerable(false) decorator is called, it modifies the enumerable property of the property descriptor.

Accessor Decorators

An Accessor Decorator is declared just before an accessor declaration.The accessor decorator is applied to the Property Descriptor for the accessor and can be used to observe, modify, or replace an accessor’s definitions.An accessor decorator cannot be used in a declaration file, or in any other ambient context (such as in a declare class).

NOTE  TypeScript disallows decorating both the get and set accessor for a single member.Instead, all decorators for the member must be applied to the first accessor specified in document order.This is because decorators apply to a Property Descriptor, which combines both the get and set accessor, not each declaration separately.

The expression for the accessor decorator will be called as a function at runtime, with the following three arguments:

  • Either the constructor function of the class for a static member, or the prototype of the class for an instance member.
  • The name of the member.
  • The Property Descriptor for the member.

NOTE  The Property Descriptor will be undefined if your script target is less than ES5.

If the accessor decorator returns a value, it will be used as the Property Descriptor for the member.

The following is an example of an accessor decorator (@configurable) applied to a member of the Point class:

  1. class Point {
  2. private _x: number;
  3. private _y: number;
  4. constructor(x: number, y: number) {
  5. this._x = x;
  6. this._y = y;
  7. }
  8. @configurable(false)
  9. get x() { return this._x; }
  10. @configurable(false)
  11. get y() { return this._y; }
  12. }

We can define the @configurable decorator using the following function declaration:

  1. function configurable(value: boolean) {
  2. return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
  3. descriptor.configurable = value;
  4. };
  5. }

A Property Decorator is declared just before a property declaration.A property decorator cannot be used in a declaration file, or in any other ambient context (such as in a declare class).

The expression for the property decorator will be called as a function at runtime, with the following two arguments:

  • Either the constructor function of the class for a static member, or the prototype of the class for an instance member.
  • The name of the member.

We can use this information to record metadata about the property, as in the following example:

  1. class Greeter {
  2. @format("Hello, %s")
  3. greeting: string;
  4. constructor(message: string) {
  5. this.greeting = message;
  6. }
  7. greet() {
  8. let formatString = getFormat(this, "greeting");
  9. return formatString.replace("%s", this.greeting);
  10. }
  11. }

We can then define the @format decorator and getFormat functions using the following function declarations:

The @format("Hello, %s") decorator here is a .When @format("Hello, %s") is called, it adds a metadata entry for the property using the Reflect.metadata function from the reflect-metadata library.When getFormat is called, it reads the metadata value for the format.

NOTE  This example requires the reflect-metadata library.See Metadata for more information about the reflect-metadata library.

Parameter Decorators

A Parameter Decorator is declared just before a parameter declaration.The parameter decorator is applied to the function for a class constructor or method declaration.A parameter decorator cannot be used in a declaration file, an overload, or in any other ambient context (such as in a declare class).

The expression for the parameter decorator will be called as a function at runtime, with the following three arguments:

  • Either the constructor function of the class for a static member, or the prototype of the class for an instance member.
  • The name of the member.
  • The ordinal index of the parameter in the function’s parameter list.

NOTE  A parameter decorator can only be used to observe that a parameter has been declared on a method.

The return value of the parameter decorator is ignored.

The following is an example of a parameter decorator (@required) applied to parameter of a member of the Greeter class:

  1. class Greeter {
  2. greeting: string;
  3. constructor(message: string) {
  4. this.greeting = message;
  5. }
  6. @validate
  7. greet(@required name: string) {
  8. return "Hello " + name + ", " + this.greeting;
  9. }
  10. }

We can then define the @required and @validate decorators using the following function declarations:

  1. import "reflect-metadata";
  2. function required(target: Object, propertyKey: string | symbol, parameterIndex: number) {
  3. let existingRequiredParameters: number[] = Reflect.getOwnMetadata(requiredMetadataKey, target, propertyKey) || [];
  4. existingRequiredParameters.push(parameterIndex);
  5. Reflect.defineMetadata(requiredMetadataKey, existingRequiredParameters, target, propertyKey);
  6. }
  7. function validate(target: any, propertyName: string, descriptor: TypedPropertyDescriptor<Function>) {
  8. let method = descriptor.value;
  9. descriptor.value = function () {
  10. let requiredParameters: number[] = Reflect.getOwnMetadata(requiredMetadataKey, target, propertyName);
  11. if (requiredParameters) {
  12. for (let parameterIndex of requiredParameters) {
  13. if (parameterIndex >= arguments.length || arguments[parameterIndex] === undefined) {
  14. throw new Error("Missing required argument.");
  15. }
  16. }
  17. }
  18. return method.apply(this, arguments);
  19. }
  20. }

The @required decorator adds a metadata entry that marks the parameter as required.The @validate decorator then wraps the existing greet method in a function that validates the arguments before invoking the original method.

Metadata

Some examples use the reflect-metadata library which adds a polyfill for an .This library is not yet part of the ECMAScript (JavaScript) standard.However, once decorators are officially adopted as part of the ECMAScript standard these extensions will be proposed for adoption.

You can install this library via npm:

  1. npm i reflect-metadata --save

TypeScript includes experimental support for emitting certain types of metadata for declarations that have decorators.To enable this experimental support, you must set the emitDecoratorMetadata compiler option either on the command line or in your tsconfig.json:

Command Line:

  1. tsc --target ES5 --experimentalDecorators --emitDecoratorMetadata

tsconfig.json:

  1. {
  2. "compilerOptions": {
  3. "target": "ES5",
  4. "experimentalDecorators": true,
  5. "emitDecoratorMetadata": true
  6. }
  7. }

When enabled, as long as the reflect-metadata library has been imported, additional design-time type information will be exposed at runtime.

We can see this in action in the following example:

  1. import "reflect-metadata";
  2. class Point {
  3. x: number;
  4. y: number;
  5. }
  6. class Line {
  7. private _p0: Point;
  8. private _p1: Point;
  9. @validate
  10. set p0(value: Point) { this._p0 = value; }
  11. get p0() { return this._p0; }
  12. @validate
  13. set p1(value: Point) { this._p1 = value; }
  14. get p1() { return this._p1; }
  15. }
  16. function validate<T>(target: any, propertyKey: string, descriptor: TypedPropertyDescriptor<T>) {
  17. let set = descriptor.set;
  18. descriptor.set = function (value: T) {
  19. let type = Reflect.getMetadata("design:type", target, propertyKey);
  20. if (!(value instanceof type)) {
  21. throw new TypeError("Invalid type.");
  22. }
  23. set.call(target, value);
  24. }
  25. }

The TypeScript compiler will inject design-time type information using the @Reflect.metadata decorator.You could consider it the equivalent of the following TypeScript:

  1. class Line {
  2. private _p0: Point;
  3. private _p1: Point;
  4. @validate
  5. @Reflect.metadata("design:type", Point)
  6. set p0(value: Point) { this._p0 = value; }
  7. get p0() { return this._p0; }
  8. @validate
  9. @Reflect.metadata("design:type", Point)
  10. set p1(value: Point) { this._p1 = value; }
  11. get p1() { return this._p1; }