Câu hỏi phỏng vấn Typescript
Câu hỏi

Explain how and why we could use property decorators in TS?

Câu trả lời

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:

How to Use Property Decorators

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.

Basic Syntax and Usage

Here is the basic syntax for a property decorator:

typescript Copy
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.

Example: Logging Property Access

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:

typescript Copy
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.

Why Use Property Decorators

Code Reusability and Separation of Concerns

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

middle

Gợi ý câu hỏi phỏng vấn

junior

What is the difference between Classes and Interfaces in Typescript?

junior

Could we use TypeScript on backend and how?

junior

How to make Arrays that can only be read, TypeScript?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào