Categories
TypeScript Answers

How to implement a TypeScript decorator?

Spread the love

Sometimes, we want to implement a TypeScript decorator.

In this article, we’ll look at how to implement a TypeScript decorator.

How to implement a TypeScript decorator?

To implement a TypeScript decorator, we should create a function that modifies an existing function and returns it.

For instance, we write

const Entity = (discriminator: string) => {
  return function (target) {
    // ...
  };
};

@Entity("cust")
export class MyCustomer {
  //...
}

to create the Entity function that returns a function.

Then we use the Entity decorator with the discriminator parameter set with the argument.

It returns a modified version of the MyCustomer class which is the function that’s being returned in Entity.

Conclusion

To implement a TypeScript decorator, we should create a function that modifies an existing function and returns it.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *