Sunday, March 31, 2024

Decorators in TypeScript — SitePoint

Must read

On this fast tip, excerpted from Unleashing the Energy of TypeScript, Steve exhibits you the right way to use decorators in TypeScript, which is a brand new characteristic 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 means. They’ve been on the scene for some time in TypeScript — albeit beneath an experimental flag. Though the Stage 2 iteration of decorators was at all times experimental, decorators have been extensively utilized in libraries like MobX, Angular, Nest, and TypeORM. TypeScript 5.0’s decorators are totally 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 methodology. With decorators, we simply do the job as soon as and the change can be supported via every methodology the decorator is connected to.

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

class Card {
  constructor(public go well with: Swimsuit, public rank: Rank) {
    this.go well with = go well with;
    this.rank = rank;

  get title(): CardName {
    return `${this.rank} of ${this.go well with}`;

  @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 technique 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');

We would like a warning message logged to the console every time card.getValue() known as. We may implement the above decorator as follows:

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

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

  return replacementMethod;

This would possibly look a little bit 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 methodology.
  • We return some methodology 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 kind has the next properties on it:

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

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

Decorators present handy syntactic sugar for including log messages — like we did within the instance above — in addition to a variety of different frequent use instances. For instance, we may 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 Energy of TypeScript, obtainable on SitePoint Premium and from e-book retailers.

Supply hyperlink

More articles


Please enter your comment!
Please enter your name here

Latest article