5 min read
•Question 23 of 48hardWhat are Decorators in TypeScript?
Metadata annotations for classes.
What You'll Learn
- What decorators are
- Types of decorators
- Basic examples
What are Decorators?
Decorators are functions that modify classes, methods, properties, or parameters. Enable with experimentalDecorators in tsconfig.
Class Decorator
code.tsTypeScript
function sealed(constructor: Function) {
Object.seal(constructor);
Object.seal(constructor.prototype);
}
@sealed
class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
}Method Decorator
code.tsTypeScript
function log(
target: any,
propertyKey: string,
descriptor: PropertyDescriptor
) {
const original = descriptor.value;
descriptor.value = function (...args: any[]) {
console.log(`Calling ${propertyKey} with`, args);
return original.apply(this, args);
};
}
class Calculator {
@log
add(a: number, b: number): number {
return a + b;
}
}Property Decorator
code.tsTypeScript
function readonly(target: any, propertyKey: string) {
Object.defineProperty(target, propertyKey, {
writable: false
});
}
class Person {
@readonly
name: string = "John";
}