You are presented with two choices.
Option one involves making changes to your enum
.
enum MyEnum {
Unknown = 1,
SomeValue,
SomeOtherValue,
}
const myIntValue = 1;
const myEnumValue = MyEnum[myIntValue]; // string
If you eliminate the value 1
from the MyEnum
definition, it will commence at 0
.
In my opinion, I am not in favor of this solution due to the fact that a numerical enum
may not be the optimal selection.
An example to ponder:
const foo = (en: MyEnum) => 42
foo(99999) // ok
The second option is as follows.
You can associate integers with the enum using a tuple:
const enum MyEnum {
Unknown = 'Unknown',
SomeValue = 'SomeValue',
SomeOtherValue = 'SomeOtherValue',
}
const MapEnum = [MyEnum.Unknown, MyEnum.SomeValue, MyEnum.SomeOtherValue] as const;
const result = MapEnum[1] // MyEnum.SomeValue
Remember, enum
/object
keys do not retain order, hence creating such a tuple dynamically may pose risks.
UPDATE
The second option functions although it comes with higher susceptibility to errors ...
enum MyEnum {
Unknown = 'Unknown',
SomeValue = 'SomeValue',
SomeOtherValue = 'SomeOtherValue',
}
type TupleUnion<U extends string, R extends any[] = []> = {
[S in U]: Exclude<U, S> extends never ? [...R, S] : TupleUnion<Exclude<U, S>, [...R, S]>;
}[U];
const MapEnum: TupleUnion<MyEnum> = [MyEnum.Unknown, MyEnum.SomeValue, MyEnum.SomeOtherValue,];
No chance of omitting any value
An alternative method without permutation:
enum MyEnum {
Unknown = 'Unknown',
SomeValue = 'SomeValue',
SomeOtherValue = 'SomeOtherValue',
}
// credits goes to https://stackoverflow.com/a/50375286
type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (
k: infer I
) => void
? I
: never;
// Credits goes to https://github.com/microsoft/TypeScript/issues/13298#issuecomment-468114901
type UnionToOvlds<U> = UnionToIntersection<
U extends any ? (f: U) => void : never
>;
type PopUnion<U> = UnionToOvlds<U> extends (a: infer A) => void ? A : never;
type IsUnion<T> = [T] extends [UnionToIntersection<T>] ? false : true;
type UnionToArray<T, A extends unknown[] = []> = IsUnion<T> extends true
? UnionToArray<Exclude<T, PopUnion<T>>, [PopUnion<T>, ...A]>
: [T, ...A];
type Result = UnionToArray<MyEnum>
const MapEnum: UnionToArray<MyEnum> = [MyEnum.Unknown, MyEnum.SomeValue, MyEnum.SomeOtherValue,];
For more examples, visit my blog