9

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.

1 Answer 1

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'
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. It works. Is it a good practice to implement things like these in TypeScript world? To be honest it looks a bit ugly. If I declare constants like these what is the point of having enum? I could have just declared string constants.
It's not bad practice as far as I know, although I have not seen it used commonly. The advantage of the way imports work in TS/JS is that the importer is explicit about what they import so no unwanted conflicts will arise from this. The advantage of using the Enum is that you can restrict function input to just that enum instead of having to specify all constant types: function c (p : MyEnum) {} vs function c2 (p : typeof MY_VALUE | typeof MY_SECOND_VALUE) {}
@TitianCernicova-Dragomir - Its 2023 and I still see the same limitation. I wonder if its really worth using TS or JS instead of Java for test automation or any serious development for that matter. In addition to OP question, there is no way to get name of enums instead of their number value. This language is a mess.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.