In this tutorial, we will explore decorators in TypeScript. Decorators are a significant feature of TypeScript that allow us to modify classes, properties, methods and accessor in a clean and readable way.
By the end of this tutorial, you will understand what decorators are, how to use them, and the various types of decorators available in TypeScript.
Prerequisites: Basic knowledge of TypeScript and object-oriented programming concepts.
Decorators are special kinds of declarations in TypeScript. They are functions that can be attached to classes, methods, accessors, properties, or parameters. Decorators use the form @expression
, where expression
must evaluate to a function that will be called at runtime with information about the decorated object.
There are four types of decorators in TypeScript:
A Class Decorator is declared just before a class declaration. The decorator function is applied to the constructor of the class and can be used to observe, modify or replace a class definition.
function sealed(constructor: Function) {
Object.seal(constructor);
Object.seal(constructor.prototype);
}
@sealed
class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
greet() {
return "Hello, " + this.greeting;
}
}
In this example, @sealed
is a class decorator and it 'seals' both the constructor and its prototype so that properties cannot be added or removed.
Method Decorators are declared just before a method declaration. The decorator function is applied to the Property Descriptor for the method, and can be used to observe, modify, or replace a method definition.
function enumerable(value: boolean) {
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
descriptor.enumerable = value;
};
}
class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
@enumerable(false)
greet() {
return "Hello, " + this.greeting;
}
}
In this example, @enumerable(false)
is a method decorator and it sets the enumerable property of the greet method descriptor to false.
Accessor Decorators are applied to the property descriptor of the accessor and can be used to observe, modify, or replace an accessor's definitions.
function configurable(value: boolean) {
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
descriptor.configurable = value;
};
}
class Point {
private _x: number;
private _y: number;
constructor(x: number, y: number) {
this._x = x;
this._y = y;
}
@configurable(false)
get x() { return this._x; }
@configurable(false)
get y() { return this._y; }
}
In this example, @configurable(false)
is an accessor decorator and it sets the configurable property of the x and y accessor descriptors to false.
A Property Decorator is declared just before a property declaration. The decorator function is applied to the property descriptor for the property, and can be used to observe, modify, or replace a property definition.
function format(target: any, propertyKey: string) {
let _val = target[propertyKey];
let getter = function () {
return "£" + _val;
};
let setter = function (newVal) {
_val = newVal;
};
if (delete target[propertyKey]) {
Object.defineProperty(target, propertyKey, {
get: getter,
set: setter,
enumerable: true,
configurable: true
});
}
}
class Product {
@format
price: number;
}
In this example, @format
is a property decorator and it modifies the price property to always return its value prefixed with '£'.
Parameter Decorators are declared just before a parameter declaration. The decorator function is applied to the function for a class constructor or method declaration.
function logParameter(target: any, propertyKey: string, parameterIndex: number) {
let metadataKey = `log_${propertyKey}_parameters`;
if (Array.isArray(target[metadataKey])) {
target[metadataKey].push(parameterIndex);
}
else {
target[metadataKey] = [parameterIndex];
}
}
class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
greet(@logParameter name: string) {
console.log("Greeting: " + name);
}
}
In this example, @logParameter
is a parameter decorator and it creates a metadata entry that records which parameters of the greet method should be logged.
Decorators are a powerful way to annotate or modify classes and class members. They provide a way to add both annotations and a meta-programming syntax for class declarations and members. Decorators are currently a stage 2 proposal for JavaScript and are available as an experimental feature of TypeScript.
Create a class decorator that will log whenever an instance of the class is created.
Create a method decorator that will log whenever the method is called.
Create a property decorator for a class that has a 'price' property. The decorator should double the price whenever it is set.
Solutions and explanations will be provided in the comments. Happy coding!