flip keys and values from a literal record type

93 Views Asked by At

In typescript, given a record literal, how do I switch the keys with the values?

That is:

type Foo = { x: "a", y: "b", z: "c" };

I wish to be able to write type Flip<X> such that:

type Bar = Flip<Foo>; // should be { a: "x", b: "y", c: "z" };

This is purely a play on types -- not on runtime values.

1

There are 1 best solutions below

0
chantey On BEST ANSWER

This can be done through the use of key remapping.

type Flip<T extends Record<any,any>> = {
     [K in keyof T as T[K]]: K 
}