How to import an Enum

北战南征 提交于 2019-12-01 13:41:25

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!