This page looks best with JavaScript enabled

Decorators in Typescript

 ·   ·  ☕ 2 min read

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.

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

    1
    2
    3
    4
    
    @specialpower
    class Human {
      // ..
    }
    

More than one decorator can be applied in one go.

1
2
3
4
5
@eat
@repeat
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.

1
2
3
4
5
function propPower(constr: any) {
  return class extends constr {
    power = "life";
  };
}

Next, we specify the decorator against the class.

1
2
3
4
@propPower
class Planet {
  constructor() {}
}

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

1
2
3
const earth = new Planet();
console.log(earth);
// 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).

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things