0

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?

2
  • You should probably post your javascript code as well Commented Nov 7, 2018 at 20:18
  • @Florian, added the JS code as well Commented Nov 7, 2018 at 20:59

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.