I have a string enum defined as follows:
export enum UserRole {
SHOP_DESIGNER = 'DG_PF00-CorpID-Designa_Shop-Designers',
SHOP_EMPLOYEE = 'DG_PF00-CorpID-Designa_Shop-Employees',
LOGISTICS_TEAM = 'DG_PF00-CorpID-Designa_Logistics',
}
I want to create a type-safe mapping from a an enum string value to its enum type:
const USER_ROLE_NAMES<string, UserRole> = ....
So I can parse an arbitrary value by querying the map:
let role: UserRole
// role = SHOP_DESIGNER
role = USER_ROLE_NAMES.get('DG_PF00-CorpID-Designa_Shop-Designers')
// role = SHOP_DESIGNER
role = USER_ROLE_NAMES.get('DG_PF00-CorpID-Designa_Shop-Employees')
// role = SHOP_DESIGNER
role = USER_ROLE_NAMES.get('DG_PF00-CorpID-Designa_Logistics')
// role = undefined
role = USER_ROLE_NAMES.get('some arbitrary string value which is not an enum value')
I already tried the following:
export const USER_ROLE_NAMES = new Map(Object.entries(UserRole).map(([key, value]: [string, UserRole]) => [value, key]));
but then the type of USER_ROLE_NAMES is Map<UserRole, string> and the map cannot be queried with a string.
If I invert the mapping
export const USER_ROLE_NAMES = new Map(Object.entries(UserRole).map(([key, value]: [string, UserRole]) => [key, value]));
then the type is correct, but the mapping is wrong ('DESIGNA_USER' => 'DG_PF00-CorpID-Designa_Users',... instead of 'DG_PF00-CorpID-Designa_Users' => 'DESIGNA_USER',...
UserRoleis strictly narrower than the union of the string literal values. It is considered a type error to use the string literal"DG_PF00-CorpID-Designa_Shop-Designers"whereUserRole.SHOP_DESIGNERis expected. Trying to get the compiler to do otherwise would be "type unsafe" according to the language. So when you say you want a type safe reverse mapping it sort of sounds like you want the opposite? Maybe we're just using different terms.Map<K, V>.get(k)returnsV | undefinedregardless of whatkis; the data structure has no notion of "definitely present" keys; and you can'tget()an arbitrary string key either unless you makeKastring. What do you want to do about those two issues? Are they relevant to the question?