Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

28. AppendArgument #37

Open
astak16 opened this issue Jul 15, 2022 · 0 comments
Open

28. AppendArgument #37

astak16 opened this issue Jul 15, 2022 · 0 comments
Labels

Comments

@astak16
Copy link
Owner

astak16 commented Jul 15, 2022

题目

题目链接: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;

知识点

  1. 通过 infer Args 获取到参数类型
  2. 把函数的参数和传入的第二个参数使用元组,组合在一起
  3. 这种方法有个问题:函数的形参不在是传入的形参了,而是变成 args_0args_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>;

知识点

  1. Parameters 可以获取到函数的参数
  2. ReturnType 可以获取到函数的返回值
@astak16 astak16 added the medium label Jul 15, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant