Home > Mobile >  Define an interface based on existing inline type for a function parameter
Define an interface based on existing inline type for a function parameter

Time:02-02

Lets say that a library has a function of this type

export declare class TheClass {
   get: (getArgs?: { arg1: string, arg2: boolean }): Promise<unknown> 
}

I need to get the type of the getArgs parameter, but I do not know how to "extract" the type from an inline type of a function parameter like that. Is it even possible?

I could of course just copy the type and define it myself but that's bad for obvious reasons if the lib changes etc.

CodePudding user response:

You can do it with a bit of index access types and the built-in Parameters conditional type. You can also use Exclude if you want to remove undefined from the type (which will be in there because of the optionality of the parameter):

export declare class TheClass {
   get: (getArgs?: { arg1: string, arg2: boolean }) => Promise<unknown> 
}

type Param = Parameters<TheClass['get']>[0]
type ParamNoUndefined = Exclude<Parameters<TheClass['get']>[0], undefined>

Playground Link

  •  Tags:  
  • Related