JavaScript Development Space

How to Use TypeScript Decorators Quickly

Decorators in TypeScript are functions applied at runtime to classes or methods to modify or extend behavior.

Enabling Decorators

To enable experimental support, add this setting to your tsconfig.json or via CLI:

json
1 {
2 "compilerOptions": {
3 "target": "ES5",
4 "experimentalDecorators": true
5 }
6 }

Class Decorators

Class decorators modify the class constructor and prototype:

ts
1 function sealed(constructor: Function) {
2 Object.seal(constructor);
3 Object.seal(constructor.prototype);
4 }
5
6 @sealed
7 class BugReport {
8 // class logic
9 }

Method Decorators

These wrap method properties and can adjust visibility or behavior:

ts
1 function enumerable(value: boolean) {
2 return (target: any, key: string, descriptor: PropertyDescriptor) => {
3 descriptor.enumerable = value;
4 };
5 }
6
7 class Greeter {
8 @enumerable(false)
9 greet() {
10 return "Hello";
11 }
12 }

Property Decorators

These apply runtime modifications to class properties:

ts
1 class MyClass {
2 @MyDecorator
3 myProperty: string;
4 }

Decorators allow modular adjustments to class structure, method behavior, and property access, enhancing TypeScript's functionality in complex applications.

JavaScript Development Space

© 2024 JavaScript Development Space - Master JS and NodeJS. All rights reserved.