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

如何在TypeScript编译产物中保留装饰器?

解决TypeScript声明文件中保留装饰器的问题

TypeScript原生不会将装饰器输出到.d.ts声明文件中——因为装饰器属于运行时语法,而声明文件核心作用是描述类型信息,默认不会包含这类运行时代码。要实现将装饰器保留在生成的声明文件里,需要借助自定义转换器工具,具体步骤如下:

步骤1:安装依赖

安装ttypescript(支持自定义转换器的TypeScript包装器)和ts-transformer-decorators(处理装饰器的转换器):

npm install ts-transformer-decorators ttypescript --save-dev

步骤2:修改tsconfig.json

在compilerOptions中添加plugins配置,指定装饰器转换器:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "declaration": true,
    "outDir": "./lib",
    "strict": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "plugins": [
      {
        "transform": "ts-transformer-decorators/transform-declaration",
        "type": "program"
      }
    ]
  },
  "include": [
    "src"
  ],
  "exclude": [
    "node_modules",
    "**/__tests__/*"
  ]
}

步骤3:使用ttypescript编译

用ttypescript替代原生tsc执行编译命令:

npx ttsc

执行完成后,生成的index.d.ts文件就会保留装饰器:

export declare class TestClass {
    @myDecorator()
    testFn(): void;
}

补充:如果不需要自动化方案,也可以手动编写并维护.d.ts文件,但这种方式在代码迭代时容易出现类型不一致,不推荐用于大型项目。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 10:05:11