簡體   English   中英

在 TypeScript 中,如何將 Union 中的所有類型轉換為該類型的數組

[英]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[]

Playground 代碼鏈接

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM