Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to extract parameter types from a function type while omitting one parameter?

Let’s say I have the following interface which defines a function:

export declare interface NavigationGuard {
    (to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext): NavigationGuardReturn | Promise<NavigationGuardReturn>;
}

I’d like to end up with this type:

export SomeNavigationGuardType = (to: RouteLocationNormalized, from: RouteLocationNormalized): NavigationGuardReturn | Promise<NavigationGuardReturn>

Utilising the original NavigationGuard type …

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I have tried utilising the utility type Parameters, extracting and using Omit to remove the next param, but the Parameters utility type is extracting to a tuple.

I’ve tried utilising:

type NavigationGuardParams = Omit<Parameters<NavigationGuard>, 'next'>

export type UseRouterNivigationGuards = {
  beforeEach?: (arg: NavigationGuardParams) => ReturnType<NavigationGuard>
  beforeResolve?: (arg: NavigationGuardParams) => ReturnType<NavigationGuard>
  afterEach?: NavigationHookAfter
}

and

type NavigationGuardParams = Omit<Parameters<NavigationGuard>, 'next'>

export type UseRouterNivigationGuards = {
  beforeEach?: (...arg: NavigationGuardParams) => ReturnType<NavigationGuard>
  beforeResolve?: (...arg: NavigationGuardParams) => ReturnType<NavigationGuard>
  afterEach?: NavigationHookAfter
}

But both results in a usage / param error, the first giving this:

"Expected 1 arguments, but got 2."

The second attempt giving:

"Argument of type ‘[RouteLocationNormalized, RouteLocationNormalized]’ is not assignable to parameter of type ‘NavigationGuardParams’."

I’m therefore asking for help! Would anyone have a trick to be able to achieve this?

>Solution :

type SomeNavigationGuardType = Parameters<NavigationGuard> extends [...infer T, next: any] ? T : never
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading