What is a Decorator?

It is a structural design pattern that lets you attach new behaviors to objects by placing these objects inside special wrapper objects that contain the behaviors (reference).

When we are using Typescript Method Decorators, they are higher-order functions that help us change method behavior or do something with the arguments.

Typescript method decorator definition: method decorator can be used to observe, modify, or replace a method definition (reference)

Now, let’s see how we can define a simple method decorator.

Setup

In order to run the Typescript code, we need to compile them using the Typescript compiler.

We need a tsconfig.json file :

We have to enable the experimentalDecorators. Also, the target should not be less than ES5.

If you do not want to use a tsconfig file you can pass these options directly:

tsc --experimentalDecorators // If you installed tsc globaly
npx tsc --experimentalDecorators // If you installed tsc in your current directory

Now by running tsc in the current directory, the typescript files will compile to javascript files and we can run them using Node.

#decorators #nodejs #typescript

Start writing your own Typescript Method Decorators
22.55 GEEK