Type definition is a necessary but tedious process in developing with TypeScript.
When a third-party library method needs to be defined separately, and the library does not export the method’s input type, you need to get the method’s input type.
For example, there is the following example function, we want to get its parameter type and return value type, so how should we implement it.
Example function.
Get the parameter type of the function
Use the predefined Parameters
to get a list of parameter types for a function.
To get the parameter types of the test
function.
Gets the type of the idx
parameter.
Let’s look at the definition of Parameters
.
|
|
We can see that it actually mainly gets the list of argument types P
of T
and returns it through infer P
, or never
if T is not a function.
Get the return value type of the function
Use the predefined ReturnType
to get a list of argument types for a function.
Get the return value type of the test
function.
|
|
Let’s look at the definition of ReturnType
again.
|
|
Very similar to Parameters
, except that the return value type of T
is obtained and returned via infer R
.