Typescript类型体操 - Fill
题目
中文
Fill是 javascript 中常用的方法, 现在让我实现类型版本的 Fill
Fill<T, N, Start?, End?>, 正如你看到的那样, Fill接受四个泛型参数, 其中 T 和 N 是必填参数, Start 和 End 是可选参数
这些参数的要求如下: T 必须是一个元组(tuple), N 可以是任何值类型, Start 和 End 必须是大于或等于 0 的整数
为了模拟真实的函数, 测试用例包含了一些边界条件, 我希望你喜欢它 😃
type exp = Fill<[1, 2, 3], 0>; // expected to be [0, 0, 0]
为了
English
Fill, a common JavaScript function, now let us implement it with types.
Fill<T, N, Start?, End?>, as you can see,Fill accepts four types of parameters, of which T and N are required parameters, and Start and End are optional parameters.
The requirements for these parameters are: T must be a tuple, N can be any type of value, Start and End must be integers greater than or equal to 0.
type exp = Fill<[1, 2, 3], 0>; // expected to be [0, 0, 0]
In order to simulate the real function, the test may contain some boundary conditions, I hope you can enjoy it 😃
答案
type Fill<
T extends unknown[],
N,
Start extends number = 0,
End extends number = T['length'],
Pending extends any[] = [],
Filled extends any[] = []
> = T extends [infer L, ...infer R]
? [
Pending['length'] extends Start
? Filled['length'] extends End
? L
: N
: L,
...Fill<
R,
N,
Start,
End,
Pending['length'] extends Start ? Pending : [...Pending, 0],
Filled['length'] extends End ? Filled : [0, ...Filled]
>
]
: [];
浙公网安备 33010602011771号