一个不错的体操问题

在群里群友发了这样一个问题:

仔细看这题其实有问题的,他上面的[number?,number?,number?]其实是不对的,length其实还是3,不符合题意length 0-3

实际类型应该是[]|[number]|[number,number]|[number,number,number]才对,ok,开搞

我的回合(解法)

export type Tuple<T, N extends number, R extends unknown[] = []> = R['length'] extends N
  ? R
  : Tuple<T, N, [T, ...R]>;

export type TupleToUnion<T> = T extends [infer F, ...infer REST] ? F | TupleToUnion<REST> : never;

export type TupleMN<
  T,
  M extends number,
  N extends number,
  I extends T[] = Tuple<T, M>,
  R extends unknown[] = [],
> = I['length'] extends N ? TupleToUnion<[...R, I]> : TupleMN<T, M, N, [...I, T], [...R, I]>;

// type a = [] | [number] | [number, number] | [number, number, number] | [number, number, number, number] | [number, number, number, number, number] | [number, number, number, number, number, number]
type a = TupleMN<number, 0, 6>;

链接

群友的回合

群友A

type BuildArray<
    Length extends number, 
    Ele = unknown, 
    Arr extends unknown[] = []
> = Arr['length'] extends Length 
        ? Arr 
        : BuildArray<Length, Ele, [...Arr, Ele]>;

type GenOptionalArr<EleType, From extends number, To extends number, CountArr extends unknown[] = [], Res = never, isBegin = false>
    = CountArr['length'] extends To
        ? Res | BuildArray<CountArr['length'], EleType>
        : CountArr['length'] extends From
            ? GenOptionalArr<
                EleType,
                From,
                To,
                [...CountArr, unknown],
                Res | BuildArray<CountArr['length'], EleType>
                ,
                true
            >
            : isBegin extends true
                ? GenOptionalArr<
                    EleType,
                    From,
                    To,
                    [...CountArr, unknown],
                    Res | BuildArray<CountArr['length'], EleType>,
                    isBegin
                >
                : GenOptionalArr<EleType, From, To, [...CountArr, unknown], Res, isBegin>


type res = GenOptionalArr<number, 3, 7>;

链接

群友B


type Arr<Elm, Min extends number, Max extends number = Min, Result extends Elm[] = [], S extends boolean = Result['length'] extends Min ? true : false> =
  Result['length'] extends Max ? Result
  : S extends true
  ? Result | Arr<Elm, Min, Max, [Elm, ...Result], true>
  : Arr<Elm, Min, Max, [Elm, ...Result]>


type a1 = Arr<string, 3>
type a2 = Arr<string, 2, 4>
type a3 = Arr<string, 0, 4>

链接

记录

评论

0 / 800
全部评论()