Decorators
4 methodsExperimental decorators (require experimentalDecorators). Stage 3 ECMAScript decorators differ.
@ClassDecorator(target: Function)Class decorator. Receives the class constructor; can return a replacement class.
Parameters
| Name | Type | Description |
|---|---|---|
| target | Function | Class constructor being decorated. |
Returns
Function | void
Example
typescript
function logged<T extends { new (...a: any[]): {} }>(Base: T) {
return class extends Base {
constructor(...a: any[]) { super(...a); console.log('constructed'); }
};
}
@logged
class Foo {}
new Foo(); // logs 'constructed'@MethodDecorator(target, key, descriptor)Method decorator. Receives the prototype, method name, and property descriptor.
Parameters
| Name | Type | Description |
|---|---|---|
| target | object | Prototype (instance) or constructor (static). |
| key | string | symbol | Method name. |
| descriptor | PropertyDescriptor | Method descriptor. |
Returns
PropertyDescriptor | void
Example
typescript
function log(target: any, key: string, desc: PropertyDescriptor) {
const orig = desc.value;
desc.value = function (...a: any[]) {
console.log('call', key, a);
return orig.apply(this, a);
};
}
class Calc {
@log
add(a: number, b: number) { return a + b; }
}@PropertyDecorator(target, key)Property decorator. Receives the prototype and property name (no descriptor).
Parameters
| Name | Type | Description |
|---|---|---|
| target | object | Prototype or constructor. |
| key | string | symbol | Property name. |
Returns
void
Example
typescript
const meta = new WeakMap();
function Column(target: any, key: string) {
meta.set(target, [...(meta.get(target) ?? []), key]);
}
class User {
@Column name!: string;
@Column email!: string;
}@ParameterDecorator(target, key, paramIndex)Parameter decorator. Receives the prototype, method name, and parameter index.
Parameters
| Name | Type | Description |
|---|---|---|
| target | object | Prototype or constructor. |
| key | string | symbol | undefined | Method name. |
| paramIndex | number | Index of the parameter. |
Returns
void
Example
typescript
function Req(target: any, key: string, idx: number) {
console.log(`@Req on ${key}[${idx}]`);
}
class Ctrl {
handler(@Req body: unknown) {}
}