Skip to content

Instantly share code, notes, and snippets.

@itsMapleLeaf
Created September 26, 2019 00:47
Show Gist options
  • Select an option

  • Save itsMapleLeaf/2ad262f37fd964be55d1e5ac87ffac5f to your computer and use it in GitHub Desktop.

Select an option

Save itsMapleLeaf/2ad262f37fd964be55d1e5ac87ffac5f to your computer and use it in GitHub Desktop.
TypeScript - filter type keys by value
type Thing = {
a: number
b: number
c: string
d: boolean
}
type Values<O> = O[keyof O]
type KeysWithType<O, T> = Values<{ [K in keyof O]: O[K] extends T ? K : never }>
type ThingNumberKeys = KeysWithType<Thing, number> // a | b
function doThing(key: KeysWithType<Thing, number>, thing: Thing) {
return thing[key]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment