Skip to content

Instantly share code, notes, and snippets.

@okaybeydanol
Created February 8, 2025 01:24
Show Gist options
  • Select an option

  • Save okaybeydanol/924d62a5912092c96542d88604d07ce8 to your computer and use it in GitHub Desktop.

Select an option

Save okaybeydanol/924d62a5912092c96542d88604d07ce8 to your computer and use it in GitHub Desktop.
TypeScript: Number Range and Subtraction Utilities (`Enumerate` and `Subtract`)
/**
* 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;
@okaybeydanol
Copy link
Author

Core utilities for numeric operations at the type level:

  1. Enumerate: Generates a tuple of numbers from 0 to N-1.
  2. Subtract: Performs type-level subtraction.

Examples:

type Numbers = Enumerate<3>; // [0, 1, 2]
type Result = Subtract<5, 2>; // 3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment