Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

type-challenges-solutions/en/medium-number-range #333

Open
utterances-bot opened this issue May 19, 2023 · 1 comment
Open

type-challenges-solutions/en/medium-number-range #333

utterances-bot opened this issue May 19, 2023 · 1 comment

Comments

@utterances-bot
Copy link

Number Range

This project is aimed at helping you better understand how the type system works, writing your own utilities, or just having fun with the challenges.

https://ghaiklor.github.io/type-challenges-solutions/en/medium-number-range.html

Copy link

A couple of solutions.

The first creates a Tuple the length of the low number and a Tuple the length of the high number (both populated with numbers), converts them both to unions using T[number] and then uses Exclude to remove the overlap of low and high.

type TupleOfLength<N extends number, R extends number[] = []> = R['length'] extends N ? R : TupleOfLength<N, [...R, R['length']]>

type NumberRange<
  L extends number,
  H extends number,
  LT extends number[] = TupleOfLength<L>,
  HT extends number[] = TupleOfLength<H>
> = Exclude<HT[number] | H, LT[number]>

The second uses the same idea as your solution (starting with nevers and then filling the rest with numbers), but uses a single utility type to achieve it

type NumberRange<L extends number, H extends number, FillWithNums extends boolean = false, 
  R extends number[] = []> = 
    R['length'] extends H ?
      L | R[number] | H:
      NumberRange<
        L,
        H,
        FillWithNums extends true ? true : R['length'] extends L ? true : false,
        [...R, FillWithNums extends true ? R['length'] : never]
      >

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

No branches or pull requests

3 participants