【Typescirpt】定义数字范围类型


数字范围参数

有的时候我们想定义一个参数的数字范围,如果范围比较小点好,比如1到5。

type Range = 1 | 2 | 3 | 4 | 5 ;

但如果数字范围很大,比如 1到100,或是1到1000,那就要写死了。

支持现状

Github上有人提了相关的建议,但还处于Open状态
https://github.com/microsoft/TypeScript/issues/15480

现实

从网上找抄了一个别的人实现的(Playground):

type BuildPowersOf2LengthArrays =
  R[0][N] extends never ? R : BuildPowersOf2LengthArrays;

type ConcatLargestUntilDone =
  B["length"] extends N ? B : [...R[0], ...B][N] extends never
    ? ConcatLargestUntilDone
    : ConcatLargestUntilDone;

type Replace = { [K in keyof R]: T }

type TupleOf = number extends N ? T[] : {
  [K in N]: 
  BuildPowersOf2LengthArrays extends infer U ? U extends never[][]
  ? Replace, T> : never : never;
}[N]

type RangeOf = Partial>["length"];

type RangeOf2 = Exclude, RangeOf> | From;

type X = RangeOf2<1,100>