typescript 如何导入枚举
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38553097/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to import an Enum
提问by Greg Gum
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. But at runtime, an error is thrown
Visual Studio 无需导入即可看到此枚举,因此不会出现编译时错误。但是在运行时,会抛出一个错误
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?
那么如何导入枚举呢?
回答by Greg Gum
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.
然后它按预期工作。
回答by luk355
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.
Cannot read property 'Foo' of undefined.
当您碰巧在 TypeScript 声明文件 ( *.d.ts
)之一中定义 Enum 时,您将遇到相同的运行时错误,因为这些文件不会转化为 JavaScript。
More details with a sample app can be found here.
可以在此处找到示例应用程序的更多详细信息。
回答by Sachin Kalia
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'
回答by Darren Yuhar
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.
IE。
export enum AccessMode in file access-mode.ts would fail. export enum AccessMode in file access-modes.ts would work.
在文件 access-mode.ts 中导出枚举 AccessMode 将失败。在文件 access-modes.ts 中导出枚举 AccessMode 会起作用。
回答by Valerii Sloboda
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 是我的枚举。