简体   繁体   English

如何导入打字稿中定义的枚举?

[英]How to import enum defined in typescript?

I have the following module defined in Typescript 我在Typescript中定义了以下模块

declare module MyTypes {

    export enum MyEnum {
        GOOD = 'Good',
        BAD = 'Bad',
        UNKNOWN = '-'
    }

   export interface MyType1 {
      myType1:string
   }

}

export default MyTypes;

In a separate file, I import it like so: 在一个单独的文件中,我将其导入为:

import MyTypes from '/my-types'
import MyType1 = MyTypes.MyType1
import MyEnum = MyTypes.MyEnum

When I refer in the code to MyEnum.GOOD, Chrome returns an exception on the console MyTypes is not defined. 当我在代码指MyEnum.GOOD, Chrome浏览器返回在控制台上异常MyTypes没有定义。 What is the appropriate way to import enums from modules in typescript? 从打字稿中的模块导入枚举的合适方法是什么?

When using declare, typescript does not create any javascript code, it only implies that it already exists. 当使用声明,打字稿不会产生任何JavaScript代码,它只是意味着它已经存在。 With interfaces it all should work well, because they are just stripped at runtime. 使用接口,所有这些都应该工作良好,因为它们只是在运行时被剥离了。 An enum on the other hand has actual string values like "Good". 另一方面,枚举具有实际的字符串值,例如“ Good”。

You can simply remove the declare keyword and it all should work. 您可以简单地删除clarify关键字,这一切都应该起作用。

module MyTypes {

    export enum MyEnum {
        GOOD = 'Good',
        BAD = 'Bad',
        UNKNOWN = '-'
    }

   export interface MyType1 {
      myType1:string
   }

}

export default MyTypes;

FYI your enum in javascript would look like this: 仅供参考,您在javascript中的枚举应如下所示:

export var MyEnum;
(function (MyEnum) {
    MyEnum["GOOD"] = "Good";
    MyEnum["BAD"] = "Bad";
    MyEnum["UNKNOWN"] = "-";
})(MyEnum || (MyEnum = {}));

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

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