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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With