Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse map key-value type to value-key

Tags:

typescript

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"
}
like image 730
hackape Avatar asked Apr 23 '26 07:04

hackape


1 Answers

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

like image 87
hackape Avatar answered Apr 25 '26 23:04

hackape



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!