Typescript中如何切掉函数参数表的最后一个参数

实现了个Prepend,将指定类型添加到元组类型的最前面:

type Prepend<Tuple extends any[], Addend> = ((_0: Addend, ..._1: Tuple) => any) extends ((..._: infer Result) => any) ? Result : never

然后利用类型递归得到Reverse

type Reverse<Tuple extends any[], Prefix extends any[] = []> = {
    0: Prefix
    1: ((..._: Tuple) => any) extends ((_0: infer First, ..._1: infer Next) => any)
        ? Reverse<Next, Prepend<Prefix, First>>
        : never
}[Tuple extends [any, ...any[]] ? 1 : 0]

停止递归的条件非常巧妙[Tuple extends [any, ...any[]] ? 1 : 0]:

type A<T extends any[]> = T extends [any, ...any[]] ? 'extends' : 'notExtends';
type B = A<[]> // 'notExtens'
type C = A<[string]> // 'extends'

出处: https://zhuanlan.zhihu.com/p/147248333