题目
中文
递归将数组展开到指定的深度
示例:
type a = FlattenDepth<[1, 2, [3, 4], [[[5]]]], 2>; // [1, 2, 3, 4, [5]]. flattern 2 times
type b = FlattenDepth<[1, 2, [3, 4], [[[5]]]]>; // [1, 2, 3, 4, [[5]]]. Depth defaults to be 1
English
Recursively flatten array up to depth times.
For example:
type a = FlattenDepth<[1, 2, [3, 4], [[[5]]]], 2>; // [1, 2, 3, 4, [5]]. flattern 2 times
type b = FlattenDepth<[1, 2, [3, 4], [[[5]]]]>; // [1, 2, 3, 4, [[5]]]. Depth defaults to be 1
If the depth is provided, it's guaranteed to be positive integer.
答案
type FlattenDepth<
T extends any[],
Depth extends number = 1,
Acc extends any[] = []
> = T extends [infer L, ...infer R]
? L extends any[]
? Acc['length'] extends Depth
? T
: [
...FlattenDepth<L, Depth, [any, ...Acc]>,
...FlattenDepth<R, Depth, Acc>
]
: [L, ...FlattenDepth<R, Depth, Acc>]
: T;
标签:...,Typescript,FlattenDepth,times,Depth,extends,体操,type
From: https://www.cnblogs.com/laggage/p/type-challenge-flatten-depth.html