on this fast tip, excerpted from unleashing the power of typescript, steve exhibits you methods 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 method. they’ve been on the scene for some time in typescript — albeit underneath 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 perform that tweaks the habits 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 can be supported by every technique the decorator is connected to.

let’s say we wish 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 title(): cardname {
    return `${this.rank} of ${this.swimsuit}`;
  }

  @deprecated // 👀 this can be 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 option 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 at any time when card.getvalue() known as. 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.title);

  perform replacementmethod(this: this, ...args: arguments): returnvalue {
    console.warn(`warning: '${methodname}' is deprecated.`);
    return goal.name(this, ...args);
  }

  return replacementmethod;
};

this would possibly look a bit complicated at first, however let’s break it down:

  • our decorator perform 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:

  • sort: the kind of the adorned property. within the instance above, this can be technique, since we’re adorning a way on an occasion of a card.
  • title: the title of property. within the instance above, that is getvalue.
  • static: a worth indicating whether or not the category factor is a static (true) or occasion (false) factor.
  • non-public: a worth indicating whether or not the category factor has a personal title.
  • entry: an object that can be utilized to entry the present worth of the category factor at runtime.
  • has: determines whether or not an object has a property with the identical title because the adorned factor.
  • get: invokes the setter on the supplied 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 quite a few different widespread use circumstances. for instance, we might create a decorator that routinely 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 power of typescript, out there on Pylogix premium and from e-book retailers.