【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<N extends number, R extends never[][]> =
  R[0][N] extends never ? R : BuildPowersOf2LengthArrays<N, [[...R[0], ...R[0]], ...R]>;

type ConcatLargestUntilDone<N extends number, R extends never[][], B extends never[]> =
  B["length"] extends N ? B : [...R[0], ...B][N] extends never
    ? ConcatLargestUntilDone<N, R extends [R[0], ...infer U] ? U extends never[][] ? U : never : never, B>
    : ConcatLargestUntilDone<N, R extends [R[0], ...infer U] ? U extends never[][] ? U : never : never, [...R[0], ...B]>;

type Replace<R extends any[], T> = { [K in keyof R]: T }

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

type RangeOf<N extends number> = Partial<TupleOf<unknown, N>>["length"];

type RangeOf2<From extends number, To extends number> = Exclude<RangeOf<To>, RangeOf<From>> | From;

type X = RangeOf2<1,100>

上一篇:eslint规则


下一篇:ts笔记-never和void