Home > Net >  Record Type Reverser
Record Type Reverser

Time:11-20

I'd like to reverse the property names and types for a record that has unique constant property values.

const VALUE = {
    field1: "fieldA",
    field2: "fieldB"
} as const

type Reversed = Reverser<typeof VALUE>

//which should yield the following type
type Reversed = {
    fieldA: "field1";
    fieldB: "field2";
} 

I dont think it is possible due to the fact that the property values arent necessarily unique. But I ask anyways ;-)

CodePudding user response:

You can use a mapped type with an as clause:

type Reverser<T extends Record<PropertyKey, PropertyKey>> = {
  [P in keyof T as T[P]]: P
}

Playground Link

The as clause will take the P key and map it to anything else. In this case we map it to the type of the property at the key P (T[P]) . For the value of the property we just use the P as the type.

  • Related