What are decorators in TypeScript?
IntermediateTypeScript interview questionBy UIRound, updated 17 November 2026
Short answer
A decorator is a function you attach to a class or class member with @name, which can observe, replace or wrap what it decorates. TypeScript has two incompatible flavours. Since TypeScript 5.0, the default is the TC39 standard decorators, called as (value, context). The older experimentalDecorators flavour, called as (target, key, descriptor), is still used by Angular, NestJS and class-validator, and supports parameter decorators and emitted type metadata.
A method decorator with standard decorators
With no compiler flag, TypeScript 5.0 and later use the standard design. A method decorator receives the original method and a context object, and may return a replacement function.
function logged<This, Args extends unknown[], Return>(
target: (this: This, ...args: Args) => Return,
context: ClassMethodDecoratorContext<This, (this: This, ...args: Args) => Return>,
) {
const name = String(context.name);
return function (this: This, ...args: Args): Return {
console.log(`Calling ${name} with`, args);
const result = target.call(this, ...args);
console.log(`${name} returned`, result);
return result;
};
}
class Calculator {
@logged
add(a: number, b: number) {
return a + b;
}
}
new Calculator().add(2, 3); // logs the call and the result 5The generics keep the decorated method's parameter and return types, so add is still (a: number, b: number) => number to callers. target.call(this, ...args) matters: the wrapper is called on the instance, and forwarding this keeps methods that read this.something working. The general wrapping idea is the same one behind memoize and debounce, covered in the decorator pattern; this page is about the TypeScript syntax and its two versions.
The context object
Standard decorators get a context with useful fields:
kind:"class","method","getter","setter","field"or"accessor".name,staticandprivate, describing the member.access: functions to read or write the member's value on an instance.addInitializer(fn): runs code when the class is defined or, for instance members, as each instance is constructed.metadata: an object shared by all decorators on the class, readable later asMyClass[Symbol.metadata](TypeScript 5.2+; the runtime needsSymbol.metadata, which you may have to polyfill).
addInitializer is how you write a @bound decorator that binds a method to its instance, so it can be passed as a callback without losing this:
function bound<This, Value extends (this: This, ...args: any[]) => any>(
_target: Value,
context: ClassMethodDecoratorContext<This, Value>,
) {
context.addInitializer(function (this: This) {
const method = (this as any)[context.name];
(this as any)[context.name] = method.bind(this);
});
}A decorator factory is a function that returns a decorator, which is how you pass options: @retry(3), @debounce(300). Field decorators cannot turn a field into a getter and setter. For that, the standard adds the accessor keyword (@observable accessor count = 0), which creates a private storage slot with a getter and setter that the decorator can wrap.
The legacy flavour: experimentalDecorators
Before 5.0, TypeScript implemented an earlier draft of the proposal behind the "experimentalDecorators": true compiler option. It is still supported and is what you get whenever that flag is on.
// tsconfig: "experimentalDecorators": true
function logged(target: object, key: string, descriptor: PropertyDescriptor) {
const original = descriptor.value;
descriptor.value = function (this: unknown, ...args: unknown[]) {
console.log(`Calling ${key} with`, args);
return original.apply(this, args);
};
return descriptor;
}Instead of a context object, a legacy method decorator receives the prototype, the property name and the property descriptor, and changes the descriptor. Legacy mode also allows parameter decorators, such as constructor(@Inject(TOKEN) private api: Api), and with emitDecoratorMetadata the compiler records constructor parameter types so a dependency injection container can read them through the reflect-metadata package.
| Standard (TS 5.0+, default) | Legacy (experimentalDecorators) |
|
|---|---|---|
| Based on | TC39 decorators proposal (stage 3) | An older draft, TypeScript-specific |
| Method signature | (value, context) |
(target, key, descriptor) |
| Parameter decorators | Not supported | Supported |
| Type metadata | context.metadata, no emitted types |
emitDecoratorMetadata plus reflect-metadata |
| Auto-accessors | accessor keyword |
Not available |
The two are not interchangeable. A decorator written for one either fails to type-check or misbehaves in the other, and a project uses one flavour at a time, decided by the experimentalDecorators flag.
Where you meet them, and which flavour each uses
- Angular uses legacy decorators:
@Component,@Injectable,@Input, and parameter decorators such as@Injectand@Optional. The Angular compiler reads them at build time. Its dependency injection is covered in dependency injection in Angular, and newer Angular code often prefers theinject()function over constructor parameter decorators. - class-validator (
@IsEmail(),@Length(2, 50)) uses legacy decorators and needsexperimentalDecorators. The same goes for NestJS and TypeORM, which also rely on emitted metadata. - MobX 6 supports both. With legacy decorators you write
@observable count = 0and callmakeObservable(this)in the constructor; with standard decorators you write@observable accessor count = 0. Its docs show both, so check which one your project'stsconfigenables. - Lit supports standard decorators with the
accessorkeyword, and legacy ones for older setups.
In an interview, saying which flavour a framework uses, and why parameter decorators force Angular and NestJS onto the legacy one, shows you understand more than the @ syntax.
Practise it
Decorators are wrappers, so the same skills apply. Type debounce and memoize so they keep the wrapped function's parameters and return type is the typing problem a method decorator has to solve, and Implement memoize() with custom cache keys and Implement a once() function are classic decorator bodies. Build a dependency injection container shows what Angular's @Injectable metadata is for.
Common follow-up questions
Do decorators run every time the method is called?
No. The decorator function runs once, when the class is defined. What runs on each call is the replacement function it returned. Initializers added with addInitializer for instance members run once per instance.
In what order are multiple decorators applied?
The decorator expressions (@a(), @b()) are evaluated top to bottom, and the decorators are applied bottom to top, so the one closest to the method wraps it first. @a @b method() behaves like a(b(method)).
Can I decorate a plain function or an object literal?
No. In both flavours, decorators apply to classes and class members only. For standalone functions, use a higher-order function such as memoize(fn) instead; see higher-order functions.
Do browsers run decorators natively?
Do not rely on it. TypeScript, Babel and other compilers turn decorators into plain function calls, so the output runs in current browsers and Node. Write them as source syntax and let the build handle the rest.
Mistakes to avoid
Copying a decorator from an Angular or NestJS tutorial into a project without
experimentalDecoratorsThe signatures differ, so it will not type-check.
Forgetting to forward
thisand the arguments in the wrapper, which breaks methods that use instance stateUsing an arrow function as the replacement method, which captures the wrong
thisDoing expensive or side-effecting work in the decorator body, which runs at class definition time, not at call time
Expecting
emitDecoratorMetadatato work with standard decoratorsIt only applies to the legacy flavour.
Sources
Practise it in code
Interviewers rarely stop at the definition. These questions open in an editor with tests.
- Type
debounceandmemoizeso they keep the wrapped function's parameters and return typeMedium25 min - Implement
memoize()with custom cache keysMedium35 minFree - Build a dependency injection container: singleton, scoped and transient lifetimes, cycle paths and async disposalHard50 min
- Implement a
once()function using closuresEasy15 min