首页 > 其他分享 >Typescript类型体操 - FlattenDepth

Typescript类型体操 - FlattenDepth

时间:2022-09-24 21:45:54浏览次数:85  
标签:... Typescript FlattenDepth times Depth extends 体操 type

题目

中文

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

示例:

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

相关文章