简体   繁体   中英

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 :

"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. 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

What could be the reason for the same. I understood that the typescript has a declaration file(of extension .ts). How can I use this in a purely JS project?

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. This is possible since const enums cannot have computed members.

Removing the const keyword should work. The inlining can only work if you use the enum in another TypeScript file.

You can set the compiler option ( TSC options ) "preserveConstEnums" as true:

tsconfig.json:

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

Or command line:

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

constant enum spec

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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