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

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

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.

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

>Solution :

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

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