Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 dont think it is possible due to the fact that the property values arent necessarily unique. But I ask anyways 😉

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading