Typescript Guide to Decorators with code examples

What are decorators in TypeScript?

Typescript 1.5 version introduced decorators, which adds extra functionality to classes methods, and properties. Decorators are one of the design patterns in an object-oriented program.

Decorators are attached to the below entities

  • class declaration
  • methods
  • properties
  • arguments or parameters

How do you write a TypeScript decorator?

Typescript Decorators are functions declared with functionality. these are declared using @metadata at compile time. These are attached to different classes and their member entities. metadata is a function that executes at runtime and attaches its behavior to runtime

Declare a decorator print function

function print(constructor: Function) {
  console.log("class decorator");
}

Add it to the class using @decorator.

@print
class employee {
  calculate() {
    return "calculation ";
  }
}
  • It calls the print function during object creation and print console.log message

What is a property decorator in TypeScript?

decorators are added to properties to add extra functionality during runtime. property functions are declared with target and propertyname. This is executed during property initialization.

const printvariable = (target: any, propertyName: string) => {
  console.log(propertyName);
};

class Employee {
  @printvariable
  firstName: string = "Eric";
}

Output

firstName;

typescript Decorator examples

Design patterns are solutions to repeated problems. This pattern allows adding functions and behavior to objects dynamically. It does affect the overall behavior of objects of a class.

Typescript decorators can be applied to

  • Methods
  • Classes
  • Properties
  • parameters
  • Accessor

These are experimental features, This might change in future versions. This will not be available to code normally.

To enable these decorators, Compiler configurations - experimentalDecorators property must be configured.

It can be done either via the command line or the tsconfig.json file in a project. Using the command line:

tsc --target ES5 --experimentalDecorators

For typescript projects, you can add “experimentalDecorators”: true in compilerOptions of the tsconfig.json file.

{
  "compilerOptions": {
    "target": "ES5",
    "experimentalDecorators": true
  }
}

Decorators syntax:

@metadata
class/function/property/variables

decorators declared with @symbole followed by name of metadata.

@metadata
``
metadata is a function

We will see the decorator examples in future posts
**Class Decorator and Examples**

You can check usage of a custom decorator for the final keyword i.e [Typescript final keyword](/typescript-final-keyword-example)