Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.8k views
in Technique[技术] by (71.8m points)

typescript - all possible keys of an union type

I want to get all available keys of an union type.

interface Foo {
  foo: string;
}

interface Bar {
   bar: string;
}

type Batz = Foo | Bar;

type AvailableKeys = keyof Batz;

I want to have 'foo' | 'bar' as result of AvailableKeys but it is never (as alternative I could do keyof (Foo & Bar), what produces exact the required type but I want to avoid to repeat the Types).

I found already the issue keyof union type should produce union of keys at github. I understand the answer, that keyof UnionType should not produce all possible keys.

So my question is: Is there an other way to get the list of all possible keys (it is ok if the verison 2.8 of tsc is required)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...