Given an object of type:
type Key2Value = {
foo: "bar"
voo: "doo"
}
Provided that the values of this type are always string type, how to construct a utility type ReverseMap<T> that reverse maps the key-value pairs to value-key pairs?
type Value2Key = ReverseMap<Key2Value>
// yields:
type Value2Key = {
bar: "foo"
doo: "voo"
}
Updated on 2024
From TypeScript 4.1 and onwards, the Key Remapping syntax brings us a more concise solution.
type ReverseMap<T extends Record<keyof T, keyof any>> = {
[K in keyof T as T[K]]: K;
};
Original Answer
type Key2Value = {
foo: "bar"
voo: "doo"
}
type ReverseMap<T extends Record<keyof T, keyof any>> = {
[P in T[keyof T]]: {
[K in keyof T]: T[K] extends P ? K : never
}[keyof T]
}
type Value2Key = ReverseMap<Key2Value>
Playground
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