简体   繁体   English

如何导入枚举

[英]How to import an Enum

I have created an enum, but I am having trouble importing and using the enum in VS15.我创建了一个枚举,但在 VS15 中导入和使用枚举时遇到问题。

This is the enum which is contained in enums.ts:这是包含在 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. Visual Studio 无需导入即可看到此枚举,因此不会出现编译时错误。 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: Visual Studio 现在给出一个编译时错误:

 "...enums is not a module ..."

So how do I import the enum?那么如何导入枚举呢?

I was missing the export keyword:我错过了 export 关键字:

 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.您将获得相同的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.当您碰巧在 TypeScript 声明文件 ( *.d.ts ) 之一中定义 Enum 时出现运行时错误,因为这些文件不会转化为 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:并在所需的 .ts 文件导入中,如下所示:

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.在文件 access-mode.ts 中导出枚举 AccessMode 将失败。 export enum AccessMode in file access-modes.ts would work.在文件 access-modes.ts 中导出枚举 AccessMode 会起作用。

As @Sachin Kalia said, I had a problem with imports.正如@Sachin Kalia 所说,我在导入时遇到了问题。

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. MessageAction 是我的枚举。

Encountered similar issue.遇到过类似的问题。 For me removing the name Enum worked.对我来说,删除名称 Enum 有效。

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 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM