In my coding project, I have an enum
called Animals
and I've been working on a function that should return the value as an enum if it is valid.
enum Animals {
WOLF = 'wolf',
BADGER = 'badger',
CAT = 'cat',
}
const coerceEnumValue = <T> (value: string, E: T): T | undefined => {
const keys = Object.keys(E);
const values = keys.map(k => E[k as any]);
const obj = lodash.zipObject(keys, values);
const key = lodash.findKey(obj, item => item === value);
if (!key) return undefined;
return E[key];
};
const selectedAnimal: Animals | undefined = coerceEnumValue('cat', Animals);
console.log(selectedAnimal);
Despite my efforts, the function is returning typeof Animals
instead of casting to Animals
.