Angular模板中无法使用export type导出的枚举问题求助
问题:Angular中无法使用ng-openapi-gen生成的枚举(模板报错ts(1362))
我通过ng-openapi-gen从OpenAPI文档生成类型定义,其中包含如下枚举:
export enum DocType { Image = 'Image' Video = 'Video' }
尝试在Angular组件模板中使用该枚举时,即使在组件类中声明了DocType = DocType,仍会触发TypeScript错误:
'DocType' cannot be used as a value because it was exported using 'export type'. ts(1362)
解决方案
确认生成代码的实际类型
ng-openapi-gen有时会将枚举转换为联合类型别名而非真实枚举,即便代码写法类似枚举。打开生成文件检查:如果是export type DocType = 'Image' | 'Video'这种形式,它仅作为类型存在,无法在模板中当作值使用。手动将类型别名转为真实枚举
将生成的联合类型改为标准枚举,注意补充枚举成员间的逗号:export enum DocType { Image = 'Image', Video = 'Video' }在组件类中显式暴露枚举
确认是真实枚举后,在组件类中将枚举绑定到实例属性:import { DocType } from './path/to/generated-file'; export class YourComponent { DocType = DocType; }之后即可在模板中正常使用:
<div *ngIf="currentDocType === DocType.Image">这是图片文档</div>配置ng-openapi-gen强制生成真实枚举
避免每次生成后手动修改,可在工具配置文件(如openapi-gen.json)中添加以下配置:{ "enumStyle": "enum" }该配置会让工具默认生成标准TypeScript枚举,而非联合类型别名。
内容的提问来源于stack exchange,提问作者Muffin
相关产品推荐
相关产品推荐

