Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript: using enum elements without specifying enum name

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.

like image 843
Sasha Shpota Avatar asked Dec 13 '17 08:12

Sasha Shpota


People also ask

Why are enums bad in TypeScript?

The they are useless at runtime argument and agree, if at runtime some code tries to change the values of one of your enums, that would not throw an error and your app could start behaving unexpectedly ( that is why Object.

What can I use instead of enums TypeScript?

Alternatives to enums: string unions and object literals.

How do you omit an enum?

Use the Exclude utility type to omit values from an enum, e.g. type WithoutMultiple = Exclude<Sizes, Sizes. Small | Sizes. Medium> . The Exclude utility type constructs a new type by excluding the provided members from the original type.

Can we change enum values in TypeScript?

You can always use a type assertion: // typescript enum example enum foo { ONE = 1, TWO = 2, THREE = 3 } (foo as any).


1 Answers

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'
like image 123
Titian Cernicova-Dragomir Avatar answered Sep 29 '22 11:09

Titian Cernicova-Dragomir