联合类型的所有可能的键 [英] all possible keys of an union type

查看:19
本文介绍了联合类型的所有可能的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取联合类型的所有可用键.

interface Foo {富:字符串;}界面栏{酒吧:字符串;}输入 Batz = Foo |酒吧;类型 AvailableKeys = keyof Batz;

我想要'foo' |'bar' 作为 AvailableKeys 的结果,但它是 never (作为替代,我可以做 keyof (Foo & Bar),什么产生了所需的类型,但我想避免重复类型).

我已经发现问题 keyof 联合类型应该产生键的联合 在 github.我理解答案,keyof UnionType 不应该产生所有可能的键.

所以我的问题是:有没有其他方法可以获取所有可能的键的列表(如果需要 tsc 的 verison 2.8 就可以了)?

解决方案

这可以在 typescript 2.8 及更高版本中使用条件类型完成.条件类型迭代联合中的类型,联合结果:

输入 Batz = Foo |酒吧;键入 KeysOfUnion;= T 扩展 T ?keyof T:从不;//AvailableKeys 基本上是 keyof Foo |酒吧钥匙//所以它将是foo";|酒吧"type AvailableKeys = KeysOfUnion;

简单的 keyof Union 不起作用的原因是因为 keyof 总是返回一种类型的可访问键,在联合的情况下,它只会是公共的键.KeysOfUnion 中的条件类型实际上将获取联合中的每个成员并获取其键,因此结果将是应用于联合中每个成员的 keyof 联合.>

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)?

解决方案

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.

这篇关于联合类型的所有可能的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆