Typescript类型体操 - FlattenDepth

题目

中文

递归将数组展开到指定的深度

示例:

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;

在线演示

posted @ 2022-09-24 21:38  Laggage  阅读(45)  评论(0编辑  收藏  举报