Typescript类型体操 - Chunk

题目

中文

你知道 lodash 吗? lodash中有一个非常实用的方法Chunk, 让我们实现它吧.
Chunk<T, N>接受两个泛型参数, 其中 T 是 tuple 类型, N是大于 1 的数字

type exp1 = Chunk<[1, 2, 3], 2>; // expected to be [[1, 2], [3]]
type exp2 = Chunk<[1, 2, 3], 4>; // expected to be [[1, 2, 3]]
type exp3 = Chunk<[1, 2, 3], 1>; // expected to be [[1], [2], [3]]

English

Do you know lodash? Chunk is a very useful function in it, now let's implement it.
Chunk<T, N> accepts two required type parameters, the T must be a tuple, and the N must be an integer >=1

type exp1 = Chunk<[1, 2, 3], 2>; // expected to be [[1, 2], [3]]
type exp2 = Chunk<[1, 2, 3], 4>; // expected to be [[1, 2, 3]]
type exp3 = Chunk<[1, 2, 3], 1>; // expected to be [[1], [2], [3]]

答案

type Chunk<
    T extends any[],
    N extends number,
    S extends any[] = [],
    ALL extends any[] = []
> = T extends [infer L, ...infer R]
    ? S['length'] extends N
        ? Chunk<T, N, [], [...ALL, S]>
        : Chunk<R, N, [...S, L], ALL>
    : S['length'] extends 0
    ? []
    : [...ALL, S];

在线演示

posted @ 2022-10-23 22:43  Laggage  阅读(54)  评论(0编辑  收藏  举报