Explain how and why we could use property decorators in TS?
Explain how and why we could use property decorators in TS?
Property decorators in TypeScript are a powerful feature that allows developers to add annotations and modify the behavior of class properties at design time. They are part of the broader category of decorators, which can also be applied to classes, methods, and accessors. Here’s a detailed explanation of how and why to use property decorators in TypeScript:
A property decorator is a function that you apply to a property declaration within a class. The decorator function is executed at runtime, but its effects are defined at design time. The syntax for a property decorator involves prefixing the decorator function with an @
symbol and placing it immediately before the property declaration.
Here is the basic syntax for a property decorator:
function MyDecorator(target: any, propertyKey: string) {
// Decorator logic here
}
class MyClass {
@MyDecorator
myProperty: string;
}
In this example, MyDecorator
is a decorator applied to myProperty
. The decorator function MyDecorator
receives two parameters:
target
: Either the constructor function of the class for a static member, or the prototype of the class for an instance member.propertyKey
: The name of the property.A common use case for property decorators is logging access to a property. Here’s how you might write a decorator to log each get and set operation on a property:
function LogAccess(target: any, propertyKey: string) {
let value = target[propertyKey];
const getter = () => {
console.log(`Get: ${propertyKey} => ${value}`);
return value;
};
const setter = (newValue: any) => {
console.log(`Set: ${propertyKey} => ${newValue}`);
value = newValue;
};
Object.defineProperty(target, propertyKey, {
get: getter,
set: setter,
enumerable: true,
configurable: true,
});
}
class User {
@LogAccess
name: string;
}
In this example, any get or set operation on User.name
will trigger a console log, providing a trace of how and when the property is accessed.
Decorators provide a clean and reusable way to abstract common functionality that can be applied across multiple properties or classes. Instead of repeating the same logic in multiple places, you can define a decorator once and apply it wherever needed. This promotes a separation of conce...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào