Decorators in TypeScript — SitePoint

Decorators in TypeScript — SitePoint

[ad_1]

On this fast tip, excerpted from Unleashing the Energy of TypeScript, Steve presentations you tips on how to use decorators in TypeScript, which is a brand new function in TypeScript 5.

Decorators have virtually been a part of ECMAScript for so long as I will be able to have in mind. Those nifty equipment allow us to regulate categories and individuals in a reusable manner. They’ve been at the scene for some time in TypeScript — albeit below an experimental flag. Even supposing the Degree 2 iteration of decorators used to be at all times experimental, decorators were extensively utilized in libraries like MobX, Angular, Nest, and TypeORM. TypeScript 5.0’s decorators are absolutely in sync with the ECMAScript proposal, which is just about able for top time, sitting at Degree 3.

Decorators allow us to craft a serve as that tweaks the conduct of a category and its strategies. Believe desiring to sneak in some debug statements into our strategies. Prior to TypeScript 5.0, we’d were caught copying and pasting the debug statements manually in each and every approach. With decorators, we do just the process as soon as and the alternate might be supported thru each and every approach the decorator is connected to.

Let’s say we wish to create a decorator for logging {that a} given approach is deprecated:

magnificence Card {
  constructor(public swimsuit: Swimsuit, public rank: Rank) {
    this.swimsuit = swimsuit;
    this.rank = rank;
  }

  get identify(): CardName {
    go back `${this.rank} of ${this.swimsuit}`;
  }

  @deprecated // 👀 It is a decorator!
  getValue(): quantity {
    if (this.rank === 'Ace') go back 14;
    if (this.rank === 'King') go back 13;
    if (this.rank === 'Queen') go back 12;
    if (this.rank === 'Jack') go back 11;
    go back this.rank;
  }

  // The brand new strategy to do it!
  get worth(): quantity {
    if (this.rank === 'Ace') go back 14;
    if (this.rank === 'King') go back 13;
    if (this.rank === 'Queen') go back 12;
    if (this.rank === 'Jack') go back 11;
    go back this.rank;
  }
}

const card = new Card('Spades', 'Queen');
card.getValue();

We wish a caution message logged to the console on every occasion card.getValue() is named. Lets enforce the above decorator as follows:

const deprecated = <This, Arguments extends any[], ReturnValue>(
  goal: (this: This, ...args: Arguments) => ReturnValue,
  context: ClassMethodDecoratorContext<
    This,
    (this: This, ...args: Arguments) => ReturnValue
  >,
) => {
  const methodName = String(context.identify);

  serve as replacementMethod(this: This, ...args: Arguments): ReturnValue {
    console.warn(`Caution: '${methodName}' is deprecated.`);
    go back goal.name(this, ...args);
  }

  go back replacementMethod;
};

This may glance somewhat complicated in the beginning, however let’s wreck it down:

  • Our decorator serve as takes two arguments: goal and context.
  • goal is the process itself that we’re adorning.
  • context is metadata in regards to the approach.
  • We go back some approach that has the similar signature.
  • On this case, we’re calling console.warn to log a deprecation realize after which we’re calling the process.

The ClassMethodDecorator kind has the next houses on it:

  • type: the kind of the embellished assets. Within the instance above, this might be approach, since we’re adorning one way on an example of a Card.
  • identify: the identify of assets. Within the instance above, that is getValue.
  • static: a price indicating whether or not the category component is a static (true) or example (false) component.
  • personal: a price indicating whether or not the category component has a non-public identify.
  • get entry to: an object that can be utilized to get entry to the present worth of the category component at runtime.
  • has: determines whether or not an object has a assets with the similar identify because the embellished component.
  • get: invokes the setter at the supplied object.

You’ll kick the tires of the code samples above in this playground.

Decorators supply handy syntactic sugar for including log messages — like we did within the instance above — in addition to a lot of different not unusual use circumstances. As an example, shall we create a decorator that mechanically binds the way to the present example or that modifies the assets descriptor of the process or magnificence.

This newsletter is excerpted from Unleashing the Energy of TypeScript, to be had on SitePoint Top class and from e book shops.



[ad_2]

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back To Top
0
Would love your thoughts, please comment.x
()
x