Platus
Platus

Reputation: 1497

Typescript decorators parameters

I would like to understand what are the different parameters of a Typescript decorator.

function myDecorator(target) {
  // do something with 'target' ...
}

In the example above, I know that target represents the function/class the decorator is attached to, but what are the other parameters of a decorator, their meaning an order, I also would like to get a link to an official documentation specifying this.

Thanks in advance.

Upvotes: 1

Views: 3067

Answers (1)

Thomas Sablik
Thomas Sablik

Reputation: 16451

A decorator expects one argument, the target it decorates and some more arguments depending on the type of the target, e.g.

Method Decorators

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.

You can find the complete lists on TypeScript Decorators for all decorator types:

  • Class Decorators

    • Only target class
  • Method Decorators

    • 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
  • Accessor Decorators

    • 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.
  • Property Decorators

    • 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.
  • Parameter Decorators

    • 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.

Additionally:

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.

[TypeScript Decorators]

You can create decorator factories with parameters as you need. They're not limited or specified.

The examples from TypeScript documentation.

Decorator:

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

applied with

@sealed x

Decorator factory:

function color(value: string) {
  // this is the decorator factory
  return function (target) {
    // this is the decorator
    // do something with 'target' and 'value'...
  };
}

applied as

@color('blue') x

Upvotes: 3

Related Questions