Decorators are special functions that dynamically alter the behavior of classes and their members.
They use the @ symbol prefix and provide a brilliant way to achieve advanced metaprogramming.
Frameworks like Angular and NestJS rely on decorators exclusively to inject dependencies automatically.
While historically an experimental feature, they are now becoming an official ECMAScript standard.
To use the older experimental decorators, you must enable a specific flag in your compiler options.
In tsconfig.json, you must set "experimentalDecorators": true.
A decorator is simply a function that receives information about the target it is attached to.
You can attach them to Classes, Methods, Properties, and Accessors seamlessly.
{
"compilerOptions": {
"target": "ES6",
"experimentalDecorators": true
}
}
A Class Decorator takes the class constructor itself as its sole argument.
It is commonly used to freeze classes, register them in a global registry, or extend behaviors.
By mutating the constructor prototype, you inject new functionality without touching internal logic.
This ensures a powerful separation of concerns across massive scalable architectures.
// The decorator function
function Logger(constructor: Function) {
console.log("Logging instantiation of class: " + constructor.name);
}
@Logger
class Person {
constructor(public name: string) {}
}
// Output immediately upon definition: Logging instantiation of class: Person
Decorators vastly reduce repetitive boilerplate code in large server-side logic frameworks.
Clean architecture leads to faster deployment cycles and fewer server-side rendering crashes.
Google heavily favors stable backend systems that respond with sub-second processing speeds.
Decorators help keep massive NestJS APIs extremely readable and highly modular.
function ReadOnly(target: any, key: string, descriptor: PropertyDescriptor) {
descriptor.writable = false;
return descriptor;
}
// Attaching this to a method makes it impossible to overwrite later!
Which special character is used to apply a decorator to a class or method?
Decorators bring highly elegant, Java-like annotations directly to the JavaScript ecosystem.
They are heavily powerful but should be used sparingly in standard vanilla TS projects.
Next, we'll see how to use TypeScript inside plain JS Projects!