Number Range
Less than 1 minuteTC-Medium
Number Range
Problem
Sometimes we want to limit the range of numbers. For example:
type result = NumberRange<2 , 9>
// | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9Solution
Approach: Grow a Tuple and Collect Lengths
Build a tuple from length Low to High, collecting each intermediate length as a union member.
type NumberRange<
Low extends number,
High extends number,
Count extends unknown[] = [],
Collecting extends boolean = false,
Result extends number = never
> = Count['length'] extends High
? Result | High
: Collecting extends true
? NumberRange<Low, High, [...Count, unknown], true, Result | Count['length']>
: Count['length'] extends Low
? NumberRange<Low, High, [...Count, unknown], true, Result | Low>
: NumberRange<Low, High, [...Count, unknown], false, Result>How it works:
- Increment
Countfrom 0 upward. - Once
Count['length']hitsLow, setCollecting = trueand start adding lengths toResult. - When
Count['length']hitsHigh, addHightoResultand return.
Key Takeaways
- A
Collectingboolean flag avoids checkingGreaterThanat every step. - This pattern — "start collecting at X, stop at Y" — is reusable for any range generation.
- The final
| Highat the base case ensures the upper bound is inclusive.
