Home >Web Front-end >JS Tutorial >Decorators in TypeScript

Decorators in TypeScript

DDD
DDDOriginal
2024-12-06 18:06:16330browse

Les Décorateurs en TypeScript

Decorators in TypeScript are a powerful feature that allows you to add metadata or modify the behavior of classes, methods, properties or parameters. They are often used in frameworks like Angular to enrich components and services. Whether you're a beginner or an experienced developer, this article guides you step-by-step through creating your own decorators to enhance your TypeScript applications.

Prerequisites

Before you begin, make sure you have the following:

  • A basic understanding of TypeScript.
  • TypeScript configured with the experimentalDecorators option enabled in your tsconfig.json file:
{
  "compilerOptions": {
    "experimentalDecorators": true
  }
}

What is a decorator?

A decorator is a function applied to a class, method, property or parameter. Preceded by the symbol @, a decorator can modify or enrich the element to which it is attached. Its main uses include:

  • Add metadata: Useful for providing additional information about a class or property.
  • Modify behavior: allows you to dynamically change the operation of a method or class.
  • Injecting dependencies: practical in modular architectures.

Creating a Component Decorator

Step 1: Define the Decorator

We will create a decorator that adds a componentName property to a class.

function Component(name: string) {
    return function (constructor: Function) {
        constructor.prototype.componentName = name;
    };
}

Explanation:

This decorator receives a name string and adds it as a property on the class prototype. All instances of this class will have access to this property.

Step 2: Apply Decorator

Let's apply the decorator to a class.

@Component('MonComposant')
class MonComposant {
    constructor() {
        console.log(`Le nom du composant est : ${this.componentName}`);
    }
}

Step 3: Test the Decorator

Let's create an instance of the class to check how it works.

const composant = new MonComposant(); 
// Affiche : Le nom du composant est : MonComposant

Creating an Input Decorator

Step 1: Define the Input Decorator

This decorator monitors and logs changes to a property.

function Input() {
    return function (target: any, propertyKey: string) {
        let value: any;

        const getter = () => {
            return value;
        };

        const setter = (newValue: any) => {
            console.log(`La valeur de ${propertyKey} a été mise à jour : ${newValue}`);
            value = newValue;
        };

        Object.defineProperty(target, propertyKey, {
            get: getter,
            set: setter,
            enumerable: true,
            configurable: true,
        });
    };
}

Explanation:

The decorator uses Object.defineProperty to intercept changes to the property. This allows you to add custom logic, such as change logging.

Step 2: Apply the Input Decorator

Let's apply it to a property.

{
  "compilerOptions": {
    "experimentalDecorators": true
  }
}

Step 3: Test the Input Decorator

Change the property to observe the effect.

function Component(name: string) {
    return function (constructor: Function) {
        constructor.prototype.componentName = name;
    };
}

Conclusion

TypeScript decorators provide an elegant and powerful way to add functionality and metadata to your classes and properties. By following this article, you have learned to:

  1. Create a component decorator to enrich a class.
  2. Implement an input decorator to monitor property changes.

These simple examples show how decorators can improve the readability and maintainability of your code. Explore more of the official TypeScript documentation to discover even more advanced applications, like using reflected metadata with Reflect.metadata.

The above is the detailed content of Decorators in TypeScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn