What are decorators in TypeScript?
Why Interviewers Ask This
This tests whether you can apply TypeScript knowledge to real-world scenarios. Interviewers are looking for clarity of thought and evidence that you've encountered this in production code.
Answer
Decorators are a stage-3 JavaScript proposal (and TypeScript feature) that allows adding metadata and modifying the behavior of classes, methods, properties, and parameters using a special syntax with @. Enable them with "experimentalDecorators": true in tsconfig. Class decorator: @sealed class MyClass { ... } — receives the class constructor, can modify or replace it. Method decorator: @log myMethod() { ... } — receives the target, method name, and property descriptor. Property decorator: @validate myProp: string. Parameter decorator: myMethod(@required param: string) { ... }. Decorators are heavily used in frameworks: Angular uses them for components (@Component), services (@Injectable); NestJS uses them for controllers (@Controller), guards, and middleware; TypeORM uses them for entity mapping (@Entity, @Column). They enable meta-programming patterns like AOP (aspect-oriented programming) for logging, validation, and authorization.
Pro Tip
Before answering, structure your response: one-line definition → real-world analogy → concrete example from a project. This makes even complex TypeScript answers easy to follow.