type-challenges-solutions icon indicating copy to clipboard operation
type-challenges-solutions copied to clipboard

type-challenges-solutions/en/medium-append-argument

Open utterances-bot opened this issue 4 years ago • 6 comments

Append Argument

This project is aimed at helping you better understand how the type system works, writing your own utilities, or just having fun with the challenges.

https://ghaiklor.github.io/type-challenges-solutions/en/medium-append-argument.html

utterances-bot avatar Jul 26 '21 19:07 utterances-bot

Although, we still have a problem. Type parameter P has a tuple with function parameters, but we need to treat them as a separate parameters

It doesn't seems like a problem - the same solution without this conversion passes the tests:

type AppendArgument<Fn, A>
  = Fn extends (...args: infer P) => infer R
    ? (...args: [...P, A]) => R
    : never

Alexsey avatar Jul 26 '21 19:07 Alexsey

@Alexsey true, it seems like I've overdone it while looking for the solution. For others to note, there is no sense in using variadic types because we proxy the P as is with no further modifications.

ghaiklor avatar Jul 27 '21 14:07 ghaiklor

I solved it by using the utility type Parameters, that is in fact same as Fn extends (...args: infer P) => infer R

type AppendArgument<Fn, A> = Fn extends (...args:any) => any ? (...args: [...Parameters<Fn>, A]) => ReturnType<Fn> : never

matiasfha avatar Apr 18 '22 13:04 matiasfha

@ghaiklor I'd modify the solution text based on Alexsey's comment, in order not to confuse readers.

gmoniava avatar Nov 25 '22 08:11 gmoniava

@gmoniava will do, thanks!

ghaiklor avatar Nov 26 '22 07:11 ghaiklor

Update for new test case:

// @ts-expect-error
AppendArgument<unknown, undefined>

type AppendArgument<Fn extends Function, A> = Fn extends (...args: infer P) => infer R ? (...args: [...P, A]) => R : never

MajorLift avatar Dec 28 '22 22:12 MajorLift