Home > Mobile >  Typescript how to remove the last parameter of a function type?
Typescript how to remove the last parameter of a function type?

Time:05-20

Assume I have a function type like this:

type Fn = (a: number, b: string, c: boolean) => void

And I want to create a new type with the last parameter removed, how can I do that?

type NewFn = RemoveLastParameter<Fn>

Expected type for NewFn:

type NewFn = (a: number, b: string) => void

CodePudding user response:

I think you want something like:

type Pop<T extends any[]> = T extends [...infer U, any] ? U : never

type RemoveLastParameter<T extends (...args: any[]) => any> =
    (...args: Pop<Parameters<T>>) => ReturnType<T>

Here Pop is a type that gets all members except the last of a tuple as U and then returns U.

Then RemoveLastParameter simply accepts any function type and constructs a new function type with the function Parameters Popped.

Proof:

type Fn = (a: number, b: string, c: boolean) => void
type NewFn = RemoveLastParameter<Fn>
// (a: number, b: string) => void


declare const newFn: NewFn
newFn(1, 'abc') // works

Playground

  • Related