Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript Map all enum values as key

Tags:

typescript

I declare a map so I can convert the numeric enum value into the value our API expects.

export const StatusMap: ReadonlyMap<Status, string> = new Map([
    [Status.NEW, 'new'],
    [Status.PENDING, 'pending'],
]);

But when I do statusMap.get(Status.NEW) it always tells me that the return value is possibly undefined. Is there a way to force a map (or similar) to contain all enum values?

And yes I know you can technically do

export enum Status {
    NEW = 'new',
    PENDING = 'pending',
}

but let's be honest, this kind of ruins the point of enums (IMO).

like image 246
Elias Avatar asked May 29 '20 08:05

Elias


1 Answers

If you can use regular object instead of Map, it can be defined as Record of enum members:

const statusMap: Record<Status, string> = {
    [Status.NEW]: 'new',
    [Status.PENDING]: 'pending',
};

Playground


Another option would be using type assertion that guarantees that all enum members are in the map:

type StatusMap = { get<T extends Status>(status: T): string }

const statusMap = new Map([
    [Status.NEW, 'new'],
    [Status.PENDING, 'pending'],
]) as StatusMap;

** Pay attention, with this approach it is not guaranteed that all the enum members are in the map at runtime, so if you choose to go this way - better to cover it by unit test.

like image 101
Aleksey L. Avatar answered Oct 19 '22 17:10

Aleksey L.