Typescript类型体操 - Append Argument
题目
中文
实现一个泛型 AppendArgument<Fn, A>,对于给定的函数类型 Fn,以及一个任意类型 A,返回一个新的函数 G。G 拥有 Fn 的所有参数并在末尾追加类型为 A 的参数。
type Fn = (a: number, b: string) => number
type Result = AppendArgument<Fn, boolean> 
// 期望是 (a: number, b: string, x: boolean) => number
English
For given function type Fn, and any type A (any in this context means we don't restrict the type, and I don't have in mind any type 😉) create a generic type which will take Fn as the first argument, A as the second, and will produce function type G which will be the same as Fn but with appended argument A as a last one.
For example,
type Fn = (a: number, b: string) => number
type Result = AppendArgument<Fn, boolean> 
// expected be (a: number, b: string, x: boolean) => number
答案
type AppendArgument<Fn extends (...params: any[]) => any, A> = Fn extends (...p: infer P) => infer R
  ? (...params: [...p: P, a: A]) => R
  : never;
 
                    
                     
                    
                 
                    
                 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号