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

能否在React中使用TypeScript 5.0装饰器?

启用TypeScript 5.0新版装饰器的方法

当然可行,你需要在TypeScript配置中做以下修改:

  • 在tsconfig.json里,将compilerOptions下的experimentalDecorators设为false(旧版装饰器依赖该选项,新版无需启用)
  • 开启decoratorsBeforeExport选项(控制装饰器语法位置,新版推荐将装饰器放在export语句之前)
  • 确保你的TypeScript版本为5.0及以上,低于该版本不支持新版装饰器

配置示例:

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ESNext",
    "strict": true,
    "experimentalDecorators": false,
    "decoratorsBeforeExport": true
  }
}

新版装饰器的调用逻辑和旧版不同,以类装饰器为例,它会直接接收类作为唯一参数:

function ClassDecorator<T extends new (...args: any[]) => {}>(target: T) {
  return class extends target {
    newProperty = "new property";
    hello = "override";
  };
}

@ClassDecorator
class Greeter {
  property = "property";
  hello: string;
  constructor(m: string) {
    this.hello = m;
  }
}

完成配置后,装饰器就会按照TypeScript 5.0的规范执行,不再使用旧版的参数逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 12:22:02