all possible keys of an union type

This can be done in typescript 2.8 and later using conditional types. Conditional types iterate over types in a union, union-ing the result:

type Batz = Foo | Bar;

type KeysOfUnion<T> = T extends T ? keyof T: never;
// AvailableKeys will basically be keyof Foo | keyof Bar 
// so it will be  "foo" | "bar"
type AvailableKeys = KeysOfUnion<Batz>; 

The reason a simple keyof Union does not work is because keyof always returns the accessible keys of a type, in the case of a union that will only be the common keys. The conditional type in KeysOfUnion will actually take each member of the union and get its keys so the result will be a union of keyof applied to each member in the union.


Instead of a union type, you need an intersection type:

type Batz = Foo & Bar;

I agree that their naming can sometimes be confusing.

Tags:

Typescript