装饰器
decorators;Nest/实验性语法。
30 分钟
装饰器
装饰器(Decorators)是一种 元编程 语法,可在类、方法、属性、参数上附加元数据或变换行为。TypeScript 5+ 支持 Stage 3 装饰器;nestjs-essentials 大量使用 @Controller、@Injectable 等装饰器构建 DI 容器。本课衔接 typescript-essentials 与 nextjs-essentials(Next 本身少用装饰器,但后端 API 层常配合 Nest)。
学习目标
- 理解装饰器执行顺序与分类
- 启用 tsconfig 中的
experimentalDecorators/ 新标准装饰器 - 阅读 NestJS 内置装饰器的使用模式
启用装饰器
// tsconfig.json
{
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"useDefineForClassFields": true
}
}
NestJS 依赖 reflect-metadata 在运行时读取参数类型,配合 emitDecoratorMetadata。
类装饰器
function sealed(constructor: Function) {
Object.seal(constructor);
Object.seal(constructor.prototype);
}
@sealed
class TrackModule {
constructor(public name: string) {}
}
方法装饰器
function log(target: unknown, propertyKey: string, descriptor: PropertyDescriptor) {
const original = descriptor.value as (...args: unknown[]) => unknown;
descriptor.value = function (...args: unknown[]) {
console.log(`Calling ${propertyKey}`, args);
return original.apply(this, args);
};
return descriptor;
}
class Greeter {
@log
greet(name: string): string {
return `Hello, ${name}`;
}
}
属性与参数装饰器
function required(_target: object, propertyKey: string) {
// 元数据标记,配合 validation 框架
}
class CreateLessonDto {
@required
title!: string;
constructor(@required title: string) {
this.title = title;
}
}
NestJS 风格示例
// 简化示意,实际由 @nestjs/common 提供
function Controller(prefix: string): ClassDecorator {
return (target) => {
Reflect.defineMetadata("path", prefix, target);
};
}
function Get(path?: string): MethodDecorator {
return (_target, _key, descriptor) => {
Reflect.defineMetadata("method", "GET", descriptor.value!);
Reflect.defineMetadata("path", path ?? "", descriptor.value!);
};
}
@Controller("tracks")
class TracksController {
@Get()
list() {
return [];
}
}