walkthroughthecode
walkthroughthecode

Reputation: 519

Get keys of union of objects in TypeScript

Is there a way to get all keys of type union type of objects { a: ...} | { b: ...} ? One thing worth mention — this type is generated dynamically.

Spent a few hours but without any luck...

Upvotes: 6

Views: 872

Answers (1)

jperl
jperl

Reputation: 5132

Conditional types follow the distributive law.

Something along these lines (or at least a start)

type Keys<T> = T extends {[key: string]: any} ? keyof T : never

type Test = Keys<{a: string} | {b: number} | {c: object}>

//type Test = "a" | "b" | "c"

Playground

Upvotes: 8

Related Questions