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
123456
{
"compilerOptions": {
"target": "ES5",
"experimentalDecorators": true
}
}
Class Decorators
Class decorators modify the class constructor and prototype:
ts
123456789
function sealed(constructor: Function) {
Object.seal(constructor);
Object.seal(constructor.prototype);
}
@sealed
class BugReport {
// class logic
}
Method Decorators
These wrap method properties and can adjust visibility or behavior:
ts
123456789101112
function enumerable(value: boolean) {
return (target: any, key: string, descriptor: PropertyDescriptor) => {
descriptor.enumerable = value;
};
}
class Greeter {
@enumerable(false)
greet() {
return 'Hello';
}
}
Property Decorators
These apply runtime modifications to class properties:
ts
1234
class MyClass {
@MyDecorator
myProperty: string;
}
Decorators allow modular adjustments to class structure, method behavior, and property access, enhancing TypeScript’s functionality in complex applications.