Decorator 是一种特殊声明 (@name),它为类、方法、属性或参数添加行为或元数据。它是 runtime 用装饰目标调用的函数,允许你以声明方式包装或注释它。
ts
() {
original = desc.;
desc. = () {
.(, args);
original.(, args);
};
}
{
() { { id }; }
}
().();
Decorator 是一种特殊声明 (@name),它为类、方法、属性或参数添加行为或元数据。它是 runtime 用装饰目标调用的函数,允许你以声明方式包装或注释它。
() {
original = desc.;
desc. = () {
.(, args);
original.(, args);
};
}
{
() { { id }; }
}
().();
Decorator 接收了方法描述符并用包装器替换它——无需触及方法体即可实现横切关注点(logging、caching、timing)。
@Controller("users") // NestJS — declares a route controller
export class UsersController {
@Get(":id") // maps GET /users/:id
findOne(@Param("id") id: string) { return id; } // param decorator injects the route param
}
@Entity() // TypeORM — maps a class to a DB table
class User { @Column() name: string; }
NestJS、Angular、TypeORM 和 class-validator 都是围绕 decorator 构建的,用于 DI、routing、ORM mapping 和 validation。
{ "experimentalDecorators": true, "emitDecoratorMetadata": true }
上面的 legacy (experimental) decorators 是 Nest/Angular/TypeORM 目前依赖的。还有更新的 TC39 Stage-3 decorators(TS 5+),具有不同的签名,这是未来标准——但大多数现有框架仍然使用 legacy 形式。
Decorators 实现了清洁、声明式的元编程——这是服务器框架和 ORM 的基础。
了解机制(包装目标的函数)和 legacy-vs-standard 的分割对于在 NestJS/Angular 生态系统中工作至关重要。