Reverse mappings in enums currently do not have literal types assigned to them; they are only of type string
. There is a feature request open at microsoft/TypeScript#50933 to add support for reverse values with literal types, but as of now, it is not part of the language.
If you need to move forward, you will have to find a workaround, which may involve using a type assertion at some point. You could create a utility type to search for an enum key based on its value type:
type ReverseEnumLookup<T, V> =
keyof { [K in keyof T as T[K] extends V ? K : never]: 0 }
This method uses key-remapping in a mapped type to filter out keys of T
that match the given value type. It operates similarly to KeysMatching
discussed in In TypeScript, how to get the keys of an object type whose values are of a given type?. Here's how it works:
type TestA = ReverseEnumLookup<typeof RadCheck, RadCheck.blank>;
// type TestA = "blank"
type TestB = ReverseEnumLookup<typeof RadCheck, RadCheck.macAddress>;
// type TestB = "macAddress"
type TestC = ReverseEnumLookup<typeof RadCheck, 12345>;
// type TestC = never
So you could proceed as follows:
const H = RadCheck[RadCheck.blank] as ReverseEnumLookup<typeof RadCheck, RadCheck.blank>;
// const H: "blank"
console.log(H) // "blank"
However, this might be more cumbersome than helpful. Instead, consider creating a utility function that utilizes this type to reverse any enum (as demonstrated in How to look for a key with value in Typescript Enum?):
function reverseEnumLookup<T extends object, const V extends T[keyof T]>(
t: T,
v: V
) {
const ret = Object.entries(t).find(e => v === e[1]);
if (ret === undefined) throw new Error("not found");
return ret[0] as ReverseEnumLookup<T, V>;
}
This approach is likely more user-friendly:
const H = reverseEnumLookup(RadCheck, RadCheck.blank);
// const H: "blank"
console.log(H); // "blank"
You could even simplify reverseEnumLookup()
to perform a direct index lookup, but the specific implementation is less important than recognizing that the desired operation is lacking a feature and requires a workaround involving at least one type assertion or similar loosening of types.
Playground link to code