Decorators in TypeScript — SitePoint

on

|

views

and

comments

[ad_1]

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

Decorators have nearly been a part of ECMAScript for so long as I can keep in mind. These nifty instruments allow us to modify courses and members in a reusable approach. They’ve been on the scene for some time in TypeScript — albeit beneath an experimental flag. Though the Stage 2 iteration of decorators was all the time experimental, decorators have been broadly 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 prepared for prime time, sitting at Stage 3.

Decorators allow us to craft a operate that tweaks the conduct of a category and its strategies. Think about needing to sneak in some debug statements into our strategies. Earlier than TypeScript 5.0, we’d have been caught copying and pasting the debug statements manually in every technique. With decorators, we simply do the job as soon as and the change will likely be supported by every technique the decorator is hooked up to.

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

class Card {
  constructor(public swimsuit: Go well with, public rank: Rank) {
    this.swimsuit = swimsuit;
    this.rank = rank;
  }

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

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

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

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

We would like a warning message logged to the console every time card.getValue() is named. We might implement 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);

  operate replacementMethod(this: This, ...args: Arguments): ReturnValue {
    console.warn(`Warning: '${methodName}' is deprecated.`);
    return goal.name(this, ...args);
  }

  return replacementMethod;
};

This may look somewhat complicated at first, however let’s break it down:

  • Our decorator operate takes two arguments: goal and context.
  • goal is the tactic itself that we’re adorning.
  • context is metadata concerning the technique.
  • We return some technique that has the identical signature.
  • On this case, we’re calling console.warn to log a deprecation discover after which we’re calling the tactic.

The ClassMethodDecorator sort has the next properties on it:

  • type: the kind of the embellished property. Within the instance above, this will likely be technique, since we’re adorning a way on an occasion of a Card.
  • identify: the identify of property. Within the instance above, that is getValue.
  • static: a price indicating whether or not the category ingredient is a static (true) or occasion (false) ingredient.
  • non-public: a price indicating whether or not the category ingredient has a non-public identify.
  • entry: an object that can be utilized to entry the present worth of the category ingredient at runtime.
  • has: determines whether or not an object has a property with the identical identify because the embellished ingredient.
  • get: invokes the setter on the offered object.

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

Decorators present handy syntactic sugar for including log messages — like we did within the instance above — in addition to plenty of different widespread use circumstances. For instance, we might create a decorator that mechanically binds the tactic to the present occasion or that modifies the property descriptor of the tactic or class.

This text is excerpted from Unleashing the Energy of TypeScript, obtainable on SitePoint Premium and from e-book retailers.

[ad_2]

Supply hyperlink

Share this
Tags

Must-read

Google Presents 3 Suggestions For Checking Technical web optimization Points

Google printed a video providing three ideas for utilizing search console to establish technical points that may be inflicting indexing or rating issues. Three...

A easy snapshot reveals how computational pictures can shock and alarm us

Whereas Tessa Coates was making an attempt on wedding ceremony clothes final month, she posted a seemingly easy snapshot of herself on Instagram...

Recent articles

More like this

LEAVE A REPLY

Please enter your comment!
Please enter your name here