Amal
Amal

Reputation: 305

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?

Upvotes: 0

Views: 809

Answers (2)

Allenaz
Allenaz

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

constant enum spec

Upvotes: 1

Felix Kling
Felix Kling

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

Related Questions