Reputation: 37989
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?
Upvotes: 117
Views: 138424
Reputation: 298
Short answer
Use.ts
extension instead of .d.ts
Explanation:
.d.ts
file does not generate the js
code on compilation.
This means it won't be available at runtime. There is a work around solution which is not always suggested is to define your enums in to .js
file but you have to be super careful about the types and you have to do it manually.
Upvotes: -1
Reputation: 803
Sometimes, you just need to restart the dev server if the grammar is ok.
In my case, I've already defined the export enum ...
. But the log console still warns me "...has no exported member...", it seems like enum
type has a different import mechanism.
But after I restarted the dev server, the errors had gone.
Upvotes: 0
Reputation: 37989
I was missing the export keyword:
export enum EntityStatus {
New = 0,
Active = 1,
Archived = 2,
Trashed = 3,
Deleted = 4
}
Then it worked as expected. (But see @Martin Braun's comment below)
Upvotes: 146
Reputation: 570
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 transpiled into JavaScript.
More details with a sample app can be found here.
Upvotes: 47
Reputation: 35
Encountered similar issue. For me removing the name Enum worked.
Before :
export enum ContentStatusEnum { New = 0, Saved = 1, Ready = 2, Sent = 3, Cancel = 4, OnError = 5 }
After:
export enum ContentStatus { New = 0, Saved = 1, Ready = 2, Sent = 3, Cancel = 4, OnError = 5 }
Upvotes: -7
Reputation: 128
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.
Upvotes: 2
Reputation: 373
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.
Upvotes: 23
Reputation: 1107
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'
Upvotes: 29