Decorators in Typescript

Decorate a class, member or property to signify its specialty.

Decorators are not available in Javascript but enable us to enhance our Typescript libraries and code. Decorators are experimental features in Typescript at this time.

A decorator is a way to annotate or modify a class, properties, functions or parameters. Decorator is specified against a target class, and has a body that indicates the decorator’s function.

A decorator exists in brought to life in two parts -

  1. Define a function to apply against target class, property etc.

    function specialpower(meta: any) {
      // do something
  2. Then, the decorator is specified against the class, member, etc.

    class Human {
      // ..

More than one decorator can be applied in one go.

class Human {
  // ..

The functions are evaluated left to right, and then, top to bottom, as applicable. The results are then called from the last evaluation from previous step to the first.

As an example, consider the below decorator to add a new property to the class.

function propPower(constr: any) {
  return class extends constr {
    power = "life";

Next, we specify the decorator against the class.

class Planet {
  constructor() {}

We can see the power added to the class without any further action from our end -

const earth = new Planet();
// class_1 { power: 'life' }

You can see the potential here - we can start adding “stuff” to props, members and classes, and take Typescript to all new levels. But remember - they are experimental and can change.

If you cannot wait to see decorators today - you can always use NestJS or Angular frameworks. They have decorator support built in and people seem to go crazy about them (I am neutral).

comments powered by Disqus