I have created an enum, but I am having trouble importing and using the enum in VS15.
This is the enum which is contained in enums.ts:
enum EntityStatus {
New = 0,
Active = 1,
Archived = 2,
Trashed = 3,
Deleted = 4
}
Visual Studio sees this enum without even importing and so does not give a compile time error. But at runtime, an error is thrown
Cannot read property 'Archived' of undefined.
So now I try to import it like I import other classes:
import {EntityStatus} from "../../core/enums";
Visual Studio now gives a compile time error:
"...enums is not a module ..."
So how do I import the enum?
In order to be able to import an enum from a different file, it has to be exported using a named or default export.
You should always use enums when a variable (especially a method parameter) can only take one out of a small set of possible values. Examples would be things like type constants (contract status: “permanent”, “temp”, “apprentice”), or flags (“execute now”, “defer execution”).
An enum is defined using the enum keyword, directly inside a namespace, class, or structure. All the constant names can be declared inside the curly brackets and separated by a comma. The following defines an enum for the weekdays. Above, the WeekDays enum declares members in each line separated by a comma.
I was missing the export keyword:
export enum EntityStatus {
New = 0,
Active = 1,
Archived = 2,
Trashed = 3,
Deleted = 4
}
Then it worked as expected.
You will get the same Cannot read property 'Foo' of undefined.
runtime error when you happen to define your Enum in one of the TypeScript Declaration files (*.d.ts
) as these files does not get transpired into JavaScript.
More details with a sample app can be found here.
Kindly try this. It works for me
enums.ts
export enum Category {Cricket,Tennis,Golf,Badminton}
and in required .ts file import like the way given below:
import {Category} from './enums'
Just ran across something similar. In my case, I had to ensure the exported enum name was different than the name of the file.
ie.
export enum AccessMode in file access-mode.ts would fail. export enum AccessMode in file access-modes.ts would work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With