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

TypeScript属性装饰器target参数传入undefined问题排查

问题原因及解决方案

原因分析

你遇到的问题是因为当前使用的是TypeScript遵循ECMAScript标准的新版装饰器,而非旧版的实验性装饰器。两者的类属性装饰器签名存在本质区别:

  • 旧版实验性装饰器中,实例属性的装饰器第一个参数target是类的原型对象;
  • 新版标准装饰器中,实例属性装饰器的第一个参数是属性的初始值(你的abc属性未设置初始值,所以是undefined),类的原型或构造函数需要通过第二个参数context的target属性获取。

你的代码写法是基于旧版实验性装饰器的预期,但tsconfig中未启用实验性装饰器,因此运行时符合新版标准的行为。

解决方案

你有两种选择:

方案一:使用新版标准装饰器(推荐)

调整装饰器签名,通过context.target获取类原型:

function annotate(a = 1, b = 2) {
    return function (initialValue: undefined, context: ClassFieldDecoratorContext) {
        console.log("类原型对象:", context.target); // 输出 MyClass.prototype
        console.log("属性名称:", context.name); // 输出 "abc"
    }
}

class MyClass {
    @annotate()
    abc: string;
}

方案二:回退到旧版实验性装饰器(不推荐,已被标记为废弃)

在tsconfig.json中启用实验性装饰器配置:

{
    "compilerOptions": {
      "module": "Node16",
      "esModuleInterop": true,
      "target": "ES2022",
      "moduleResolution": "Node16",
      "experimentalDecorators": true, // 启用实验性装饰器
      "emitDecoratorMetadata": true // 可选,若需要元数据支持则添加
    },
    "lib": ["ES2022"]
}

启用后,你原来的代码会按照旧版逻辑运行,target参数将变为MyClass.prototype。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 01:57:35