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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With