![](/img/trans.png)
[英]Typescript: How to convert an array of keys into a union type of objects?
[英]In TypeScript, how to convert all types within a Union to an array of that type
假設我有以下內容:
type UnionType = CustomType1 | CustomType2 | CustomType3;
// is there a way to accomplish this, without having to type it out like so.
type UnionTypeArr = CustomType1[] | CustomType2[] | CustomType3[];
您可以使用分布式條件類型( T extends X ? Y : Z
形式的條件類型,其中T
是泛型類型參數)將聯合拆分為其成員,對每個成員執行轉換,並將結果組合到另一個聯盟:
type DistribArrayify<T> = T extends unknown ? Array<T> : never;
type UnionType = CustomType1 | CustomType2 | CustomType3;
type UnionTypeArr = DistribArrayify<UnionType>;
// type UnionTypeArr = CustomType1[] | CustomType2[] | CustomType3[]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.