You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript中如何以const形式正确定义类装饰器?

正确定义符合TypeScript编译器要求的类装饰器

要同时满足编译器「优先使用const箭头函数」和「禁止直接使用Function类型」的要求,有两种合规的写法:

写法一:使用TypeScript内置的ClassDecorator类型

直接利用官方预定义的类型,简洁且不会触发类型警告:

export const reportableClassDecorator: ClassDecorator = (constructor) => {
  // 在这里编写你的装饰器逻辑,比如给类添加方法或属性
  constructor.prototype.report = function() {
    console.log(`当前类:${this.constructor.name}`);
  };
};

写法二:保留泛型约束的箭头函数版本

如果需要更精确的类型控制(比如装饰器要返回新构造函数),可以把手册里的function声明改成箭头函数,保留原有的泛型约束:

export const reportableClassDecorator = <T extends { new (...args: any[]): {} }>(constructor: T) => {
  // 示例:返回一个继承原类的新构造函数,添加额外功能
  return class extends constructor {
    report() {
      console.log(`报告:${this.constructor.name} 实例已创建`);
    }
  };
};

为什么这两种写法可行?

  • 第一种的ClassDecorator是TypeScript官方内置类型,它内部已经规范了构造函数的类型约束,不会触发「禁止使用Function类型」的提示。
  • 第二种通过泛型T extends { new (...args: any[]): {} }明确限定了参数是能生成对象的构造函数类型,比直接写Function类型更精确,编译器会认可这种写法,同时用const箭头函数满足了编译器对声明方式的偏好。

内容的提问来源于stack exchange,提问作者LeO

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 13:03:12