Last active
December 27, 2023 16:22
-
-
Save niedzielski/4ba76f963099011ee2e84bae8f9e7b2b to your computer and use it in GitHub Desktop.
Reverse a type's keys and values in TypeScript.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| type Reverse<T> = {[V in T[keyof T] & keyof T]: keyof T} |
Author
What I wrote looks incorrect. Yours looks right but I think you'll want to constraint the keys to valid key types only (eg, keyof any, string | number | symbol, or PropertyKey):
type Reverse<T> = {[V in T[keyof T] & PropertyKey]: keyof T}I think this is what I used the most recent time I needed to flip keys and values:
export type Inverse<T extends Invertible> = {
[Key in keyof T as T[Key]]: Key
}
export type Invertible = Record<PropertyKey, PropertyKey>
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Would this not be
instead?