题目
中文
有时我们需要限制数字的范围...
示例:
type result = NumberRange<2 , 9> // | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
English
Sometimes we want to limit the range of numbers...
For examples.
type result = NumberRange<2 , 9> // | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
答案
type NumberRange<
L extends number,
H extends number,
CArr extends any[] = [],
OArr extends unknown[] = [unknown],
R extends number = H
> = H extends CArr['length']
? R
: L extends CArr['length']
? NumberRange<OArr['length'], H, [any, ...CArr], [unknown, ...OArr], L | R>
: NumberRange<L, H, [...CArr, any], [unknown, ...OArr]>;
知识点
- 使用元组的
length
进行计数 - 将结果保存到泛型参数
R
内, 避免递归层数过多导致H
超过50
tsc报possible infinity loop
错