links: TypeScript MOC


Consider this example:

enum ApprovalState {  
 Rejected = 'REJECTED',  
 Approved = 'APPROVED',  
 NotDetermined = 'NOT DETERMINED',  
}

If you receive the values of enum from api response in json (ex: REJECTED) In order to map it to key you can do something like this

function getEnumKeyByEnumValue<T extends {[index:string]:string}>(myEnum:T, enumValue:string):keyof T|null {  
    let keys = Object.keys(myEnum).filter(x => myEnum[x] == enumValue);  
    return keys.length > 0 ? keys[0] : null;  
}

This function takes enum and the string and returns the enum key


tags: typescript , enum