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.
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) => numberThis question is ported from the original article by @maciejsikora
Change the following code to make the test cases pass (no type check errors).
type AppendArgument<Fn extends (...args: any[]) => any, A> = (
...args: [...Parameters<Fn>, x: A]
) => ReturnType<Fn>How it works:
Fn to be a function type with any arguments.Fn and the new argument A into a new tuple. The arguments name (x) is arbitrary, we could have used any other name.Fn using ReturnType<Fn>.type AppendArgumentNoBuiltIns<
Fn extends (...args: any[]) => any,
A,
> = Fn extends (...args: infer P) => infer R ? (...args: [...P, A]) => R : neverHow it works:
Fn extends a function type with any arguments and infer the type of the arguments (P) and return type (R).Fn and the new argument A and also with the same return type R ((...args: [...P, A]) => R).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.
Be the first to access the course, unlock exclusive launch bonuses, and get special early-bird pricing before anyone else.
Only 27 Spots left
Get 1 month early access
Pre-Launch discount