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

TypeScript方法装饰器的descriptor返回undefined,求排查原因

问题分析与解决

你的代码存在两个核心问题,直接导致装饰器的descriptor输出undefined,同时还包含语法错误:

1. 装饰器函数的语法错误

你错误地使用type function来定义装饰器函数——type是TypeScript中用于定义类型别名的关键字,不能用来定义实际的函数。这个语法错误会导致装饰器无法被正确解析,参数传递自然出现异常。

2. 未启用装饰器所需的TypeScript配置

装饰器属于TypeScript的实验性特性,必须在tsconfig.json中启用相关配置,否则装饰器无法正常工作:

  • 必须开启experimentalDecorators
  • 若需要获取元数据,可额外开启emitDecoratorMetadata

修正后的代码

// 移除错误的type关键字,正确定义方法装饰器
function logger34(target: any, propertyName: string, descriptor: PropertyDescriptor){
    console.log(descriptor);
    console.log(propertyName);
    console.log(target);
}

class x {
    class2: string = "12";
    constructor() {}
    @logger34
    y() {
        console.log(`the name of the person is `); // 顺便修复模板字符串的语法错误(缺失$符号)
    }
}

// 实例化类触发装饰器执行
new x();

对应的tsconfig.json配置示例

{
  "compilerOptions": {
    "target": "ES5",
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "strict": true
  }
}

运行修正后的代码,就能正常输出descriptor的内容了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 16:34:52