Decorators

Decorators are proposed for a future version of JavaScript, butthe Angular team really wanted to use them, and they have been included inTypeScript.

Decorators are functions that are invoked with a prefixed @ symbol, andimmediately followed by a class, parameter, method or property. Thedecorator function is supplied information about the class, parameter ormethod, and the decorator function returns something in its place, ormanipulates its target in some way. Typically the "something" a decoratorreturns is the same thing that was passed in, but it has been augmented in someway.

Decorators are quite new in TypeScript, and most use cases demonstrate theuse of existing decorators. However, decorators are just functions, and areeasier to reason about after walking through a few examples.

Decorators are functions, and there are four things (class, parameter,method and property) that can be decorated; consequently there are fourdifferent function signatures for decorators:

  • class: declare type ClassDecorator = (target: TFunction) => TFunction | void;
  • property: declare type PropertyDecorator = (target: Object, propertyKey: string | symbol) => void;
  • method: declare type MethodDecorator = (target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor) => TypedPropertyDescriptor | void;
  • parameter: declare type ParameterDecorator = (target: Object, propertyKey: string | symbol, parameterIndex: number) => void;
    Readers who have played with Angular will notice that these signatures donot look like the signatures used by Angular specific decorators like@Component().

Notice the () on @Component. This means that the @Component iscalled once JavaScript encounters @Component(). In turn, this means thatthere must be a Component function somewhere that returns a function matchingone of the decorator signatures outlined above. This is an example of thedecorator factory pattern.

If decorators still look confusing, perhaps some examples will clear things up.

原文: https://angular-2-training-book.rangle.io/handout/features/decorators.html