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": true5 }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 }56 @sealed7 class BugReport {8 // class logic9 }
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 }67 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 @MyDecorator3 myProperty: string;4 }
Decorators allow modular adjustments to class structure, method behavior, and property access, enhancing TypeScript's functionality in complex applications.