Skip to content

Number Range

题目

Sometimes we want to limit the range of numbers... For examples.

ts
type result = NumberRange<2, 9>; //  | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9

解答

ts
type NumberRange<
  L extends number,
  H extends number,
  Idx extends 1[] = L extends 0 ? [] : [1, 1],
  Res = never
> = Idx["length"] extends H
  ? H | Res
  : NumberRange<L, H, [...Idx, 1], Idx["length"] | Res>;

精选

TypeScript PlayGround

ts
interface Defer<T> {
  next: T;
  result: unknown;
}

interface Result<T> extends Defer<Result<T>> {
  result: T;
}

type Range<
  L extends number,
  H extends number,
  Idx extends 1[] = L extends 0 ? [] : [1, 1],
  Res = never
> = Defer<
  Idx["length"] extends H
    ? Result<H | Res>
    : Range<L, H, [...Idx, 1], Idx["length"] | Res>
>;

type For<T> = T[Extract<"next", keyof T>];

type GetNext_5Times<T> = For<T> extends infer T
  ? For<T> extends infer T
    ? For<T> extends infer T
      ? For<T> extends infer T
        ? For<T>
        : never
      : never
    : never
  : never;

type GetNext_50Times<T> = GetNext_5Times<T> extends infer T
  ? GetNext_5Times<T> extends infer T
    ? GetNext_5Times<T> extends infer T
      ? GetNext_5Times<T> extends infer T
        ? GetNext_5Times<T> extends infer T
          ? GetNext_5Times<T> extends infer T
            ? GetNext_5Times<T> extends infer T
              ? GetNext_5Times<T> extends infer T
                ? GetNext_5Times<T> extends infer T
                  ? GetNext_5Times<T>
                  : never
                : never
              : never
            : never
          : never
        : never
      : never
    : never
  : never;

type GetNext_200Times<T> = GetNext_50Times<T> extends infer T
  ? GetNext_50Times<T> extends infer T
    ? GetNext_50Times<T> extends infer T
      ? GetNext_50Times<T>
      : never
    : never
  : never;

type NumberRange<L extends number, R extends number> = GetNext_200Times<
  Range<L, R>
>["result"];

How this work

Released under the MIT License.