Skip to content

Instantly share code, notes, and snippets.

@niedzielski
Last active December 27, 2023 16:22
Show Gist options
  • Select an option

  • Save niedzielski/4ba76f963099011ee2e84bae8f9e7b2b to your computer and use it in GitHub Desktop.

Select an option

Save niedzielski/4ba76f963099011ee2e84bae8f9e7b2b to your computer and use it in GitHub Desktop.
Reverse a type's keys and values in TypeScript.
type Reverse<T> = {[V in T[keyof T] & keyof T]: keyof T}
@maheshjag
Copy link
Copy Markdown

Would this not be

type Reverse<T> = {[V in T[keyof T]]: keyof T}

instead?

@niedzielski
Copy link
Copy Markdown
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}

Ex

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