Skip to content

TypeScript Decorators API

TypeScript decorators — special declarations for annotating classes and their members (experimental).

1 class · 4 methods

Decorators

4 methods

Experimental decorators (require experimentalDecorators). Stage 3 ECMAScript decorators differ.

@ClassDecorator(target: Function)

Class decorator. Receives the class constructor; can return a replacement class.

Parameters

NameTypeDescription
targetFunctionClass 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

NameTypeDescription
targetobjectPrototype (instance) or constructor (static).
keystring | symbolMethod name.
descriptorPropertyDescriptorMethod 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

NameTypeDescription
targetobjectPrototype or constructor.
keystring | symbolProperty 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

NameTypeDescription
targetobjectPrototype or constructor.
keystring | symbol | undefinedMethod name.
paramIndexnumberIndex 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) {}
}