Skip to content

Decorator

一句话解释

decorator 是 TypeScript feature (experimental) 那个修改 or enhances 类, 方法, 属性, or 参数 using @decorator 语法.

用大白话说

Decorators 是函数那个修改类 and 它们的成员. 你 apply 它们使用 @ 语法: @log above 方法. 它们是 experimental feature 那个需要启用 experimentalDecorators in tsconfig.

Decorators are commonly used for logging, validation, dependency injection, and ORM mapping. Frameworks like NestJS and TypeORM rely heavily on decorators.

There are several types: class decorators, method decorators, property decorators, and parameter decorators. Each receives different arguments describing the target being decorated. The decorator standard is still evolving (TC39 proposal).

示例

typescript
function log(target: any, key: string, desc: PropertyDescriptor) {
  const orig = desc.value;
  desc.value = function(...args: any[]) {
    console.log(`Calling ${key}`);
    return orig.apply(this, args);
  };
}

class Calc {
  @log add(a: number, b: number) { return a + b; }
}

@log decorator wraps 添加方法到 log 每个 call.

相关术语

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回术语表