February 22, 2023

Decorators in TypeScript

Decorators provide a mechanism to metaprogramming syntax in TypeScript, which is a programming technique basically means "writing code that writes code".

Decorators allow us to decorate members of a class, or a class itself, with extended functionality. This is a function that we can hook into our code, to extend with some behavior and helps us to write code abstractions and provide extension mechanism.

When you apply a decorator to a class or a class member, it will actually call a function that is going to receive details of target (what is being decorated), and the decorator implementation will then be able to transform the code dynamically (e.g. adding extra functionality, and reducing boilerplate code).

The decorators are used on class itself and its members:

  • class definition
  • properties
  • methods
  • accessors
  • parameters

Note that:

Decorators are a stage 2 proposal for JavaScript and are available as an experimental feature of TypeScript.

Before using decorators in TypeScript, we need to enable it. If the decorator support is not enabled and you try to compile a TypeScript file/project that is using decorator, it will give you this error:

 error TS1219: Experimental support for decorators is a feature that is subject to change 
 in a future release. Set the 'experimentalDecorators' option in your 'tsconfig' or 'jsconfig'
 to remove this warning.

We have two ways to enable decorators support in TypeScript:

  • You can enable decorators support at compile time. When using the TypeScript Compiler CLI (tsc), we need to provide additional flag --experimentalDecorators:
    tsc --experimentalDecorators
    
  • When working in a project that has a tsconfig.json file, to enable decorators support you can add the experimentalDecorators property (with value true) to the compilerOptions object:
    {
      "compilerOptions": {
        "experimentalDecorators": true
      }
    }
    

Related Post(s):

No comments:

Post a Comment