-
Notifications
You must be signed in to change notification settings - Fork 2
Open
Labels
Description
题目
题目链接:AppendArgument
实现 AppendArgument
,满足下面需求,将第二个参数放到函数参数的最后一位
import type { Equal, Expect } from "@type-challenges/utils";
type Case1 = AppendArgument<(a: number, b: string) => number, boolean>;
type Result1 = (a: number, b: string, x: boolean) => number;
type Case2 = AppendArgument<() => void, undefined>;
type Result2 = (x: undefined) => void;
type cases = [Expect<Equal<Case1, Result1>>, Expect<Equal<Case2, Result2>>];
答案
方法一
type AppendArgument<Fn, A> = Fn extends (...args: infer Args) => infer R
? (...args: [...Args, A]) => R
: never;
知识点
- 通过
infer Args
获取到参数类型 - 把函数的参数和传入的第二个参数使用元组,组合在一起
- 这种方法有个问题:函数的形参不在是传入的形参了,而是变成
args_0
、args_1
...
方法二
type AppendArgument<Fn, A> = Fn extends (...args: infer Args) => infer R
? (...args: [...rest: Args, x: A]) => R
: never;
知识点
解决方法二中,形参不是传入的形参问题。
方法三
type AppendArgument<Fn extends (...args: any) => any, A> = (
...args: [...Parameters<Fn>, A]
) => ReturnType<Fn>;
知识点
Parameters
可以获取到函数的参数ReturnType
可以获取到函数的返回值