42
loading...
This website collects cookies to deliver better user experience
mkdir ts-decorators
cd ts-decorators
npm init -y
npm i -D typescript @types/node
@types/node
has the type definitions for the node.js standard libraries like path
, fs
etc.{
// ...
"scripts": {
"build": "tsc"
}
}
tsconfig.json
file.{
"compilerOptions": {
"target": "ES5",
"experimentalDecorators": true
}
}
npm i ts-node -D
dev
script to the package.json
file:{
"scripts": {
"build": "tsc",
"start": "ts-node ./src/index.ts"
}
}
const classDecorator = (target: Function) => {
// do something with your class
}
@classDecorator
class Man {}
const addAgeToMan = (target: Function) => {
// "target" is the constructor of the previous class
return class extends target {
age = 24
}
}
@addAgeToMan
class Man {}
Man
has an age
property of 24
:const man = new Man();
console.log(man.age); // 24
target
, propertyKey
and descriptor
const myDecorator = (target: Object, propertyKey: string, descriptor: PropertyDescriptor) => {
// Do something
}
class Man {
walk() {
console.log('Walking in 3... 2... 1')
}
}
Man
). The second(propertyKey
) param contains the name of the method in string format. The last parameter is the property descriptor, a set of information that defines a property behavior. This can be used to observe, modify, or replace a method definition. We'll circle back to this later.target
and propertyKey
parameter. The only difference is that you don’t get the property descriptor
.class Man {
@measure
walk() {
console.log('Walking in 3... 2... 1')
}
}
Man
class has a walk()
method, to measure it's execution time, we can use the @measure
decorator.import { performance } from "perf_hooks";
const measure = (
target: Object,
propertyKey: string,
descriptor: PropertyDescriptor
) => {
const originalMethod = descriptor.value;
descriptor.value = function (...args) {
const start = performance.now();
const result = originalMethod.apply(this, args);
const finish = performance.now();
console.log(`Execution time: ${finish - start} milliseconds`);
return result;
};
return descriptor;
};
Launching in 3... 2... 1... 🚀
Execution time: 1.2983244 milliseconds
const changeValue = (value) => (target: Object, propertyKey: string) => {
Object.defineProperty(target, propertyKey, { value });
};
changeValue
function returns a decorator that change the value of the property based on the value passed from your factory.class Man {
@changeValue(100)
age = 24;
}
const man = new Man();
console.log(man.age); // 100
drink
which requires the age to be at least 21.class Man {
drink() {
console.log('Drinking!')
}
}
minimumAge
is a factory decorator. It takes the age parameter, which indicates how much age is needed to drink.class Man {
age = 10;
@minimumAge(21)
drink() {
console.log('Drinking!')
}
}
const man = new Man()
man.drink()
// Console shows:
Not enough age!