简体   繁体   English

将枚举从 Typescript 转换为 JavaScript 时出错

[英]Error on converting enum from Typescript to JavaScript

I have an enum in Typescript let's say我在打字稿中有一个枚举让我们说

export const enum CarType {
    SED = "Sedan"
}

The JavaScript code after build :构建后的 JavaScript 代码:

"use strict";
Object.defineProperty(exports,"_esModule, { value: true })

:

So basically the js code doesn't have the logic, instead only the .d.ts file has the same.所以基本上js代码没有逻辑,只有.d.ts文件有逻辑。 When I build it using tsc command and export the JavaScript code to a react app, while accessing this enum like: CarType.SED , it is giving an error like - Cannot read property SED of undefined当我使用tsc命令构建它并将 JavaScript 代码导出到反应应用程序时,在访问这个枚举时,如: CarType.SED ,它给出了一个错误,如 - Cannot read property SED of undefined

What could be the reason for the same.什么可能是相同的原因。 I understood that the typescript has a declaration file(of extension .ts).我知道打字稿有一个声明文件(扩展名为 .ts)。 How can I use this in a purely JS project?如何在纯 JS 项目中使用它?

From the documenation :文档中

Const enums can only use constant enum expressions and unlike regular enums they are completely removed during compilation.常量枚举只能使用常量枚举表达式,并且与常规枚举不同,它们在编译期间被完全删除。 Const enum members are inlined at use sites. Const 枚举成员在使用站点内联。 This is possible since const enums cannot have computed members.这是可能的,因为 const 枚举不能有计算成员。

Removing the const keyword should work.删除const关键字应该可以工作。 The inlining can only work if you use the enum in another TypeScript file.只有在另一个 TypeScript 文件中使用枚举时,内联才有效。

You can set the compiler option ( TSC options ) "preserveConstEnums" as true:您可以将编译器选项( TSC 选项)“preserveConstEnums”设置为 true:

tsconfig.json: tsconfig.json:

{
  "compilerOptions": {
    "preserveConstEnums": true,
    ...
  },
  ...
}

Or command line:或者命令行:

tsc --preserveConstEnums true path/to/some_file.ts

constant enum spec 常量枚举规范

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM