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

TypeScript装饰器调用报错:运行时传参与预期不符

TypeScript装饰器报错解决:运行时传参不匹配

这个报错是因为TypeScript当前默认启用了Stage 3装饰器提案(新规范),而你写的是旧版类装饰器的代码,两者的函数签名不兼容:

  • 旧版类装饰器仅接收constructor一个参数
  • 新版类装饰器会传入两个参数:目标构造函数,以及包含装饰器元数据的ClassDecoratorContext对象

给你两种解决方式:

方式一:适配新版装饰器规范

修改装饰器函数,兼容新的参数签名(不需要用到context的话可以直接忽略它):

function Frozen(constructor: Function, _: ClassDecoratorContext) {
    Object.freeze(constructor);
}

@Frozen
class Sample {
    id: number;

    constructor(id: number) {
        this.id = id;
    }
}

方式二:启用旧版装饰器模式

如果是跟着旧版官方文档学习,直接在tsconfig.json里配置使用旧规范:

{
  "compilerOptions": {
    "experimentalDecorators": true,
    "emitDecoratorMetadata": false // 不需要元数据的话保持false,需要则设为true
  }
}

配置完成后,你原来的代码就能正常运行了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 02:44:54