[英]How to get a flattened tuple type of a tuple of tuples?
考慮我有一個元組元組:
type Example = [[3,5,7], [4,9], [0,1,10,9]];
我想創建一個實用程序類型Flatten<T>
這樣Flatten<Example>
給出:
type FlatExample = Flatten<Example>;
// type FlatExample = [3,5,7,4,9,0,1,10,9];
對於我的用例,您可以假設元組僅嵌套一層。 元組可以有任何大小。
我怎樣才能做到這一點?
為此,您需要遞歸條件類型。 這將在 4.1 中得到完全支持:
type Example = [[3,5,7], [4,9], [0,1,10,9]];
type Flatten<T extends any[]> =
T extends [infer U, ...infer R] ? U extends any[] ? [...U, ... Flatten<R>]: []: []
type FlatExample = Flatten<Example>;
編輯
更簡單的版本,對 jcalz 的支持:
type Example = [[3,5,7], [4,9], [0,1,10,9]];
type Flatten<T extends any[]> =
T extends [any, ...infer R] ? [...T[0], ... Flatten<R>]: []
type FlatExample = Flatten<Example>;
/編輯
即使在今天,您也可以破解一個版本(需要額外的間接性來欺騙編譯器以允許遞歸條件類型,從概念上講,這等效於上面更簡單的版本):
type Example = [[3, 5, 7], [4, 9], [0, 1, 10, 9]];
type Flatten<T extends any[]> = T extends [infer U, ...infer R] ? {
1: U extends any[] ? [...U, ...Flatten<R>] : [],
2: []
}[U extends any[] ? 1 : 2] : [];
type FlatExample = Flatten<Example>;
只是為了好玩,4.1,廣義扁平化版本。
type Example = [[3,5,7], [4,9, [10, 12, [10, 12]]], [0,1,10,9, [10, 12]]];
type Flatten<T extends any[]> =
T extends [infer U, ...infer R] ?
U extends any[] ?
[...Flatten<U>, ... Flatten<R>]: [U, ... Flatten<R>]: []
type FlatExample = Flatten<Example>;
注意:雖然 4.1 更支持遞歸類型,但您仍然會遇到編譯器硬編碼限制,例如類型實例化深度和總類型實例(因為這樣的遞歸類型會生成大量類型實例化)。 所以請謹慎使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.