![](/img/trans.png)
[英]TypeScript union of strings not assignable to union of tuples in function
[英]Typescript - concat union of Parameters tuples
我有一個參數聯合:
type Params = [{ name: string }] | [{ x: number, y: number } | ...];
我想連接聯合中的每個元組(獨立於聯合中的元組數量)並得到如下結果:
type ParamsJoined = [{ name: string, x: number, y: number, ... }];
我不能使用像const這樣的技巧,因為類型Params
是使用Parameters
和函數聯合上的分布條件類型動態創建的。
我該怎么做?
好吧,你需要三件事來實現:
第一個是一個簡單的,包括映射類型和infer
關鍵字:
type UnderlyingType<T> = T extends Array<infer R> ? R : T;
對於第二個,你必須參考這個問題。
第三個有點高級,你應該參考這個問題。
最后,您將獲得如下內容:
type U1 = UnderlyingType<Params>
type SplitTyped = SplitType<U1>
type FinalType = Spread<SplitTyped[0],SplitTyped[1]>
編輯:對於未知數量的類型參數(僅限於某處),您可以利用SpreadTuple
類型映射來實現
type SpreadTuple<T extends any[], L extends number = T['length']> = L extends 0 ? never
: L extends 1 ? T[0]
: L extends 2 ? Spread<T[0], T[1]>
: L extends 3 ? Spread<T[0], Spread<T[1], T[2]>>
: L extends 4 ? Spread<T[0], Spread<T[1],Spread<T[2],T[3]>>>
: never; // continiue to somewhere
然后您可以根據需要使用它:
type FinalType = SpreadTuple<SplitTyped>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.