Decorators in TypeScript provide a way to modify or enhance the behavior of classes, methods, properties, or parameters. They are a special kind of function that can be attached to classes or their members.
Decorators are experimental in TypeScript, so you need to enable them explicitly using the --experimentalDecorators
compiler flag.
Steps to Enable Decorators:
-
Command Line: Use the
tsc
(TypeScript compiler) command with the--experimentalDecorators
flag.tsc --target ES5 --experimentalDecorators
-
tsconfig.json: Alternatively, enable decorators in the TypeScript configuration file.
{ "compilerOptions": { "target": "ES5", "experimentalDecorators": true } }
Example with Decorators:
In this example, we’ll define two decorators, f
and g
, and apply them to a method in a class.
function f() {
console.log("f(): evaluated");
return function(target, propertyKey: string, descriptor: PropertyDescriptor) {
console.log("f(): called");
};
}
function g() {
console.log("g(): evaluated");
return function(target, propertyKey: string, descriptor: PropertyDescriptor) {
console.log("g(): called");
};
}
class C {
@f()
@g()
method() {}
}
Explanation:
-
Decorator
f
:- When applied to the method
method()
, it printsf(): evaluated
during evaluation. - It then returns a function that prints
f(): called
when invoked.
- When applied to the method
-
Decorator
g
:- Similarly, it prints
g(): evaluated
during evaluation. - It also returns a function that prints
g(): called
.
- Similarly, it prints
-
Class
C
:- The
method()
is decorated with both@f()
and@g()
decorators. - The decorators are evaluated in the order they are applied, from bottom to top (
@f()
first, then@g()
).
- The
Output:
When the class C
is used and method()
is called, the following output will be printed:
f(): evaluated
g(): evaluated
f(): called
g(): called
Decorators in TypeScript are powerful tools to modify the behavior of classes, methods, and properties dynamically. They can be used in frameworks like Angular for things like dependency injection or routing.