最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - TypeScript: using enum elements without specifying enum name - Stack Overflow

programmeradmin8浏览0评论

I have an enumeration which I want to use in several places. Let's say enum like this:

export enum MyEnum {
    MY_VALUE,
    MY_SECOND_VALUE
}

Every time I use it I have to specify enum name in front of the value, eg:

MyEnum.MY_VALUE

Q: Is it possible to import the enum in the way that I wont need to specify the name?

I'd like to use the value directly:

MY_VALUE

In java world it is called static import. But I haven't found anithing like that TypeScript.

My TypeScript version is 2.5.3.

I have an enumeration which I want to use in several places. Let's say enum like this:

export enum MyEnum {
    MY_VALUE,
    MY_SECOND_VALUE
}

Every time I use it I have to specify enum name in front of the value, eg:

MyEnum.MY_VALUE

Q: Is it possible to import the enum in the way that I wont need to specify the name?

I'd like to use the value directly:

MY_VALUE

In java world it is called static import. But I haven't found anithing like that TypeScript.

My TypeScript version is 2.5.3.

Share Improve this question asked Dec 13, 2017 at 8:13 Sasha ShpotaSasha Shpota 10.3k15 gold badges93 silver badges177 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 9

There is no syntax for static imports in Typescript.

You could assign the value member to a constant and use that:

const  MY_VALUE = MyEnum.MY_VALUE;

If you define the enum values as constants in the exporting module, you can easily import the values anywhere else you need to use them:

// enumModule .ts
export  enum MyEnum {
    MY_VALUE,
    MY_SECOND_VALUE
}

export const  MY_VALUE = MyEnum.MY_VALUE;
export const  MY_SECOND_VALUE = MyEnum.MY_SECOND_VALUE;

// Other file.ts
import { MY_SECOND_VALUE, MY_VALUE } from './enumModule'
发布评论

评论列表(0)

  1. 暂无评论