Skip to content

Instantly share code, notes, and snippets.

@AkinAguda
Last active January 26, 2024 22:53
Show Gist options
  • Save AkinAguda/4e7a77616ddf5a0f105ca94e6e75b84e to your computer and use it in GitHub Desktop.
Save AkinAguda/4e7a77616ddf5a0f105ca94e6e75b84e to your computer and use it in GitHub Desktop.
A `Range` type in typescript that ensures that a value is within a certain range of positive values (not inclusive of the last)
// Convert string to number
type ToNumber<S> = S extends `${infer N extends number}` ? N : never;
// Creates an array with a particular length
type ArrayWithLength<
T extends number,
A extends number[] = number[],
> = A["length"] extends T ? A : ArrayWithLength<T, [...A, A["length"]]>;
// Generates a union type with all the numbers from zero -> n
type ZeroToN<N extends number> = ToNumber<
Exclude<keyof ArrayWithLength<N, []>, keyof []>
>;
// Only shows the difference between both union types
type Range<M extends number, N extends number> = Exclude<
ZeroToN<N>,
ZeroToN<M>
>;
const value: Range<5, 10> = 4; // Type '4' is not assignable to type '5 | 6 | 7 | 8 | 9'.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment