Skip to content

Instantly share code, notes, and snippets.

@sanex3339
Created July 21, 2019 00:20
Show Gist options
  • Save sanex3339/3d55dd2eb9ecb57feb09165d758f6366 to your computer and use it in GitHub Desktop.
Save sanex3339/3d55dd2eb9ecb57feb09165d758f6366 to your computer and use it in GitHub Desktop.
type PrependToArray <Element, TArray extends _Iterator<any, any[]> = []> =
((head: Element, ...args: TArray) => any) extends ((...args: infer TResult) => any)
? TResult
: TArray;
type ArrayLength <TArray extends _Iterator<any, any[]>> = TArray['length'];
type NextIteratorValue <TArray extends _Iterator<any, any[]>> = PrependToArray<any, TArray>;
type _Iterator<Index extends number = 0, Current extends any[] = []> = {
0: _Iterator<Index, NextIteratorValue<Current>>,
1: Current,
}[
ArrayLength<Current> extends Index
? 1
: 0
];
type _NumberRange <
StartIterator extends _Iterator<Start, any>,
EndIterator extends _Iterator<End, any>,
Start extends number,
End extends number,
Total extends number
> = {
0: _NumberRange<
NextIteratorValue<StartIterator>,
EndIterator,
Start,
End,
ArrayLength<StartIterator> | Total
>,
1: Total
}[
StartIterator extends EndIterator
? 1
: 0
];
type NumberRange <Start extends number = 0, End extends number = 1, Total extends number = Start> =
_NumberRange<_Iterator<Start>, _Iterator<End>, Start, End, Total>;
const foo: NumberRange<0, 40> = 3;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment