Decorations 2 - Satttoshi/github-wiki-generator GitHub Wiki

Decorators in TypeScript

Decorators in TypeScript are a feature that allow you to add metadata, functionality, or modify the behavior of a class, method, property, or parameter at design time. They are a form of declaration and can be attached to any declaration type.

Usage

function log(property: any) {
    console.log("Property: ", property);
}

class Example {
    @log
    property: string;
}

In this example, a decorator named log is created. It logs the property name when applied to a property declaration. The @log syntax is used to apply the decorator to the property of the Example class.

Benefits

Decorators provide a way to modify or enhance the behavior of classes and their members. Some possible use cases include:

  • Logging: Decorators can be used to log method calls, property accesses, or class instantiations.
  • Validation: Decorators can be used to validate function parameters or property values.
  • Dependency Injection: Decorators can be used to inject dependencies into classes or methods.
  • Memoization: Decorators can be used to cache function results.

Decorators enable a more modular and maintainable code structure. They allow you to separate cross-cutting concerns from the core logic, making it easier to update or modify specific aspects of a class or its members without impacting the overall codebase.

Note: Decorators are still an experimental feature in TypeScript and require the experimentalDecorators compiler option to be enabled.

⚠️ **GitHub.com Fallback** ⚠️