#191Medium

Append Argument

Implement the `AppendArgument<Fn, A>` type, that appends a new argument to parameters of a function type. Learn TypeScript function types in this medium-level challenge on TypeScriptPro.

In this medium-level challenge, you'll implement the AppendArgument<Fn, A> type, that appends a new argument to parameters of a function type. This can be done with built-ins but it's a good exercise to understand how to manipulate function types in TypeScript.

Challenge Instructions: Append Argument

Medium

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

This question is ported from the original article by @maciejsikora

Change the following code to make the test cases pass (no type check errors).

Loading...

Video Walkthrough

Detailed Explanation

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

How it works:

Alternative solution without using TypeScript built-ins

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

How it works:

This challenge helps you understand TypeScript's advanced type system and how to apply this concept in real-world scenarios.

This challenge is originally from here.

Share this challenge

Join early, learn faster.

Be the first to access the course, unlock exclusive launch bonuses, and get special early-bird pricing before anyone else.

No spam, unsubscribe at any time. We respect your privacy.

Limited Availability

Only 27 Spots left

Early Access

Get 1 month early access

>75% Off

Pre-Launch discount