问题
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?
回答1:
I was missing the export keyword:
export enum EntityStatus {
New = 0,
Active = 1,
Archived = 2,
Trashed = 3,
Deleted = 4
}
Then it worked as expected.
回答2:
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.
回答3:
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'
回答4:
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.
回答5:
As @Sachin Kalia said, I had a problem with imports.
I have changed this:
import {MessageAction, MessageDTO} from '../../../generated/dto';
to this:
import {MessageDTO} from '../../../generated/dto';
import {MessageAction} from '../../../generated/dto'
MessageAction is my enum.
来源:https://stackoverflow.com/questions/38553097/how-to-import-an-enum