Search code examples
typescripttype-level-computation

flip keys and values from a literal record type


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.


Solution

  • 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 
    }