10 questionsA decorator is a special kind of declaration prefixed with @ that can be attached to a class, method, property, or parameter to observe, modify, or replace its definition — it's essentially a function that runs at class-definition time, wrapping or annotating the target.
function Log(target: any, propertyKey: string) {
console.log(`Decorating: ${propertyKey}`);
}
class Example {
@Log
greet() { return 'hi'; }
}
Real-world example
Automatically registering a class as a route handler or a component just by attaching a decorator to it.
Likely follow-ups
- Do you need a special compiler flag to use decorators, and is that changing?
tsconfig & Compiler Options
Set "experimentalDecorators": true in compilerOptions — without it, the @ decorator syntax produces a compile error under the legacy decorator implementation used by frameworks like older versions of Angular and NestJS.
// tsconfig.json
{
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true
}
}
Real-world example
Enabling decorator support to build a NestJS or Angular application, both of which rely heavily on decorators.
Likely follow-ups
- What does 'emitDecoratorMetadata' additionally enable, and which frameworks rely on it?
tsconfig & Compiler Options
A class decorator receives the class's constructor function as its argument and can inspect it, add static properties, or return a brand-new constructor that replaces the original entirely (e.g. to wrap the class with extra behavior).
function Sealed(constructor: Function) {
Object.seal(constructor);
Object.seal(constructor.prototype);
}
@Sealed
class Greeter {
greet() { return 'Hello'; }
}
Real-world example
Automatically sealing a class to prevent further properties being added, enforcing a fixed shape at runtime.
Likely follow-ups
- Can a class decorator completely replace the class with a different implementation?
Classes: Access Modifiers Abstract Classes & Implements
A method decorator receives the target (the class prototype), the method's name, and its PropertyDescriptor (which includes the original 'value' function) — it can wrap or replace that function on the descriptor to add behavior like logging or timing around every call.
function LogCalls(target: any, key: string, descriptor: PropertyDescriptor) {
const original = descriptor.value;
descriptor.value = function (...args: any[]) {
console.log(`Calling ${key} with`, args);
return original.apply(this, args);
};
}
class Calculator {
@LogCalls
add(a: number, b: number) { return a + b; }
}
Real-world example
Automatically logging every call to a service method, or adding timing/performance measurement without modifying the method body.
Likely follow-ups
- How would you write a method decorator that catches and logs any error the method throws?
Function Types Overloads & Optional/Default Parameters
A decorator factory is a function that RETURNS a decorator, letting you pass custom configuration arguments to customize the decorator's behavior per-use — plain decorators can't accept arguments directly since the decorator call signature is fixed by the target/context.
function MinLength(min: number) {
return function (target: any, key: string) {
// ... validation logic using 'min'
};
}
class User {
@MinLength(8)
password: string = '';
}
Real-world example
Configuring a validation decorator with a specific rule, like @MinLength(8) or @Range(0, 100).
Likely follow-ups
- Can decorator factories be composed or combined with other decorators on the same member?
Function Types Overloads & Optional/Default Parameters
When several decorators are stacked on one declaration, their evaluation (the outer factory calls, top to bottom) happens top-to-bottom, but their actual APPLICATION (invoking the returned decorator function on the target) happens bottom-to-top — similar to function composition, the closest decorator to the declaration runs first.
function First() { console.log('First: factory evaluated'); return () => console.log('First: applied'); }
function Second() { console.log('Second: factory evaluated'); return () => console.log('Second: applied'); }
class Example {
@First()
@Second()
method() {}
}
// Logs: First: factory evaluated, Second: factory evaluated, Second: applied, First: applied
Real-world example
Debugging an unexpected order of side effects when multiple decorators (e.g. @Log and @Cache) are stacked on the same method.
Likely follow-ups
- Does this same evaluate-top-down-apply-bottom-up rule apply to parameter decorators as well?
Modules
A property decorator receives only the target and the property key — NOT a PropertyDescriptor, since class fields aren't guaranteed to exist on the prototype at decoration time — so it typically can't directly wrap the property's get/set behavior itself, but is often used alongside metadata (e.g. reflect-metadata) to register validation rules applied later.
import 'reflect-metadata';
function Required(target: any, propertyKey: string) {
const required = Reflect.getMetadata('required', target) || [];
Reflect.defineMetadata('required', [...required, propertyKey], target);
}
class User {
@Required
email!: string;
}
Real-world example
Building a validation library (like class-validator) that collects decorator metadata to later validate object instances.
Likely follow-ups
- Why can't a property decorator directly intercept reads/writes the way a method decorator can wrap a function?
Reflect & Metadata
A parameter decorator receives the target, the method name it belongs to, and the parameter's index within that method's argument list — commonly used by dependency-injection frameworks (like NestJS or Angular) to record which constructor parameters need which service injected.
function Inject(token: string) {
return function (target: any, propertyKey: string | undefined, parameterIndex: number) {
console.log(`Inject ${token} at param ${parameterIndex} of ${propertyKey ?? 'constructor'}`);
};
}
class UserService {
constructor(@Inject('DB_CONNECTION') private db: any) {}
}
Real-world example
Recording which service a dependency-injection container should inject into each constructor parameter, as NestJS does.
Likely follow-ups
- How does the DI container actually USE the metadata recorded by a parameter decorator at runtime?
Generics
The new standard decorators (supported without experimentalDecorators, targeting a stable ECMAScript proposal) use a different, standardized signature and context object, don't support the old parameter-decorator form for constructor parameters, and are designed to eventually work identically across all JS engines — whereas legacy decorators are TypeScript/Babel-specific and predate final standardization.
// New standard decorator signature
function loggedMethod(originalMethod: any, context: ClassMethodDecoratorContext) {
return function (this: any, ...args: any[]) {
console.log(`Calling ${String(context.name)}`);
return originalMethod.apply(this, args);
};
}
Real-world example
Migrating a codebase from legacy experimentalDecorators to the new standardized decorators as frameworks adopt the final spec.
Likely follow-ups
- Why have major frameworks like Angular and NestJS been slow to migrate off legacy decorators?
tsconfig & Compiler Options
Because a decorator can arbitrarily replace or wrap the thing it decorates at definition time, bundlers and static analyzers can't always predict the final shape of a decorated class without actually running the decorator logic — this can hurt tree-shaking and makes some tooling (and some developers) less confident reasoning about a decorated class's true behavior just by reading its declaration.
// A decorator could theoretically replace 'greet' with something unrelated:
function Mystery(target: any, key: string, descriptor: PropertyDescriptor) {
descriptor.value = () => 'surprise!'; // completely different behavior
}
class Greeter {
@Mystery
greet() { return 'hello'; } // never actually runs
}
Real-world example
Being cautious when reviewing a heavily-decorated codebase, since a method's actual runtime behavior may not match its visible source code.
Likely follow-ups
- How do frameworks typically mitigate this readability concern despite relying heavily on decorators?
Design Patterns in JavaScript