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

如何在.js文件中用JSDoc @typedef声明TypeScript enum?

如何用JSDoc在JS文件中声明TypeScript const enum

背景:存在无法迁移至TypeScript的遗留JS代码,需被TS模块导入。需要通过JSDoc实现声明,且JSDoc原生的@enum与TS的enum不兼容,目标是让tsc生成如下.d.ts内容:

declare const enum MyEnum {
  Apple = "apple",
  Banana = "banana",
  Carrot = "carrot",
}

之前的失败尝试

1. 使用const断言

const MyEnum = /** @type {const} */ {
  Apple: "apple",
  Banana: "banana",
  Carrot: "carrot",
};

生成的.d.ts仅为只读对象类型,并非TS的const enum:

declare const MyEnum: {
  Apple: "apple";
  Banana: "banana";
  Carrot: "carrot";
};

2. 错误的@typedef语法

/**
 * @typedef {enum { Apple = 'apple', Banana = 'banana', Carrot = 'carrot' }} MyEnum // ❌ 语法无效
 */

该写法不符合JSDoc规范,无法被TypeScript正确解析。

正确实现方式

要让tsc生成目标的const enum声明,你可以在JS文件的JSDoc中直接使用TypeScript的const enum语法,配合@declare标记,同时确保tsconfig.json中开启allowJs: true和declaration: true。

代码示例

/**
 * @declare
 * const enum MyEnum {
 *   Apple = "apple",
 *   Banana = "banana",
 *   Carrot = "carrot"
 * }
 */

// 若需要导出供TS模块使用的JS对象实例
/** @type {typeof MyEnum} */
export const MyEnum = {
  Apple: "apple",
  Banana: "banana",
  Carrot: "carrot"
};

生成的.d.ts内容

运行tsc --allowJs --declaration后,会生成:

declare const enum MyEnum {
    Apple = "apple",
    Banana = "banana",
    Carrot = "carrot"
}
export declare const MyEnum: MyEnum;

如果不需要导出JS对象实例,仅保留@declare的enum声明即可得到你目标中的.d.ts内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 01:24:51