Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Record Type Reverser

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 don't think it is possible due to the fact that the property values aren't necessarily unique.

like image 486
robkuz Avatar asked Aug 30 '26 05:08

robkuz


1 Answers

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.

like image 196
Titian Cernicova-Dragomir Avatar answered Sep 01 '26 12:09

Titian Cernicova-Dragomir



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!