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.
Before you begin, make sure you have the following:
{ "compilerOptions": { "experimentalDecorators": true } }
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:
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.
Let's apply the decorator to a class.
@Component('MonComposant') class MonComposant { constructor() { console.log(`Le nom du composant est : ${this.componentName}`); } }
Let's create an instance of the class to check how it works.
const composant = new MonComposant(); // Affiche : Le nom du composant est : MonComposant
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.
Let's apply it to a property.
{ "compilerOptions": { "experimentalDecorators": true } }
Change the property to observe the effect.
function Component(name: string) { return function (constructor: Function) { constructor.prototype.componentName = name; }; }
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:
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!