Home > Software engineering >  How to infer type for arguments for function?
How to infer type for arguments for function?

Time:05-22

I have a type declaration like this to exclude the return union type:

export type ExcludeReturnType<T extends (...args: any[]) => any, R> = (...args: any) => Exclude<ReturnType<T>, R>

type Orig = (a: number) => string | void
type Result = ExcludeReturnType<Orig, void> // (...args: any[]) => string
type Expected = (a: number) => string

But right now it will just turn all parameters into any[]. How can I preserve the type of the original function?

Playground

CodePudding user response:

Use the Parameters utility type:

export type ExcludeReturnType<T extends (...args: any[]) => any, R> = 
  (...args: Parameters<T>) => Exclude<ReturnType<T>, R>
type Orig = (a: number, b: string) => string | void
type Result = ExcludeReturnType<Orig, void> 
// type Result = (a: number, b: string) => string

Playground

  • Related