装饰器
约 347 字大约 1 分钟
2026-02-09
装饰器是什么
装饰器本质是函数,用于在类定义阶段扩展类或类成员行为。
function Sealed() {
return function <T extends new (...args: any[]) => object>(target: T) {
Object.seal(target)
Object.seal(target.prototype)
}
}
@Sealed()
class UserService {}配置说明
很多后端框架仍基于“传统装饰器语义”:
{
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true
}
}如需运行时元数据,通常还要安装:
pnpm add reflect-metadata并在入口文件引入:
import 'reflect-metadata'常见装饰器类型
- 类装饰器(
ClassDecorator) - 方法装饰器(
MethodDecorator) - 属性装饰器(
PropertyDecorator) - 参数装饰器(
ParameterDecorator) - 访问器装饰器(
get/set)
方法装饰器示例:统计耗时
function Profile(): MethodDecorator {
return (_target, key, descriptor: PropertyDescriptor) => {
const original = descriptor.value as (...args: any[]) => unknown
descriptor.value = async function (...args: any[]) {
const start = Date.now()
const result = await original.apply(this, args)
const cost = Date.now() - start
console.log(`[profile] ${String(key)}: ${cost}ms`)
return result
}
}
}
class ApiService {
@Profile()
async fetchUser(id: number) {
return { id, name: 'zjs' }
}
}类装饰器示例:添加原型方法
function WithHello(): ClassDecorator {
return (target: any) => {
target.prototype.sayHello = function () {
console.log('hello')
}
}
}
@WithHello()
class Greeter {}执行顺序(传统语义)
同一声明上,大致顺序是:
- 参数装饰器
- 方法/访问器/属性装饰器
- 类装饰器
实践建议
- 装饰器用于横切逻辑(日志、鉴权、缓存)时收益最大
- 业务核心流程不要过度依赖“隐式注入”
- 团队需统一装饰器语义(传统 vs 标准),避免混用
