Typescript Guide to Decorators with code examples
- Admin
- Mar 6, 2024
- Typescript
What Are Decorators in TypeScript?
Decorators were introduced in TypeScript version 1.5 to extend the functionality of classes, methods, and properties. They serve as one of the design patterns in object-oriented programming.
Decorators can be attached to the following entities:
- Class declarations
- Methods
- Properties
- Arguments or parameters
How Do You Write a TypeScript Decorator?
TypeScript Decorators are functions declared with specific functionality. They are declared using @metadata
at compile time and are attached to different classes and their member entities.
metadata is a function that executes at runtime and attaches its behavior accordingly.
Let’s declare a decorator print function:
function print(constructor: Function) {
console.log("class decorator");
}
Add it to the class using @decorator:
@print
class Employee {
calculate() {
return "calculation";
}
}
This calls the print function during object creation and prints a console.log message.
What Is a Property Decorator in TypeScript?
Decorators can be added to properties to provide additional functionality during runtime. Property functions are declared with target and propertyName, and they execute during property initialization.
const printVariable = (target: any, propertyName: string) => {
console.log(propertyName);
};
class Employee {
@printVariable
firstName: string = "Eric";
}
Output
firstName;
TypeScript Decorator Examples
Design patterns offer solutions to recurring problems. This particular pattern enables the addition of functions and behavior to objects dynamically, thereby affecting the overall behavior of class objects.
TypeScript decorators can be applied to:
- Methods
- Classes
- Properties
- Parameters
- Accessors
These features are experimental and may change in future versions. They are not available for normal code usage.
To enable decorators, the experimentalDecorators
property must be configured in compiler settings, either via the command line or the tsconfig.json
file.
Using the command line:
tsc --target ES5 --experimentalDecorators
For TypeScript projects, you can add “experimentalDecorators”: true in the compilerOptions
of the tsconfig.json file:
{
"compilerOptions": {
"target": "ES5",
"experimentalDecorators": true
}
}
Decorators syntax:
@metadata
class/function/property/variables
Decorators are declared with @symbol
followed by the name of the metadata, where metadata is a function.
We will explore more decorator examples in future posts.
@metadata
metadata is a function
We will see the decorator examples in future posts Class Decorator and Examples
For usage of a custom decorator, you can refer to the final keyword example in TypeScript