Created
February 8, 2025 01:24
-
-
Save okaybeydanol/924d62a5912092c96542d88604d07ce8 to your computer and use it in GitHub Desktop.
TypeScript: Number Range and Subtraction Utilities (`Enumerate` and `Subtract`)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Generates a tuple of numbers from 0 up to (but not including) N. | |
| * Used internally for numeric operations like subtraction. | |
| * | |
| * Example: | |
| * type Numbers = Enumerate<3>; // [0, 1, 2] | |
| */ | |
| export type Enumerate< | |
| N extends number, | |
| Acc extends number[] = [], | |
| > = Acc['length'] extends N ? Acc : Enumerate<N, [...Acc, Acc['length']]>; | |
| /** | |
| * Subtracts two numbers at the type level. | |
| * Used internally for limiting the depth of nested paths. | |
| * | |
| * Example: | |
| * type Result = Subtract<5, 2>; // 3 | |
| */ | |
| export type Subtract< | |
| A extends number, | |
| B extends number, | |
| > = Enumerate<A> extends [...Enumerate<B>, ...infer R] ? R['length'] : 0; |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Core utilities for numeric operations at the type level:
Enumerate: Generates a tuple of numbers from0toN-1.Subtract: Performs type-level subtraction.Examples: