Reputation: 305
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?
Upvotes: 0
Views: 809
Reputation: 1109
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
Upvotes: 1
Reputation: 816472
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.
Upvotes: 1