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.

1
2
3
4
5
6
function test(lzwme: string, idx: number) {
  return {
    lzwme,
    idx,
  };
}

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.

1
2
type TestArgsType = Parameters<typeof test>;
// TestArgsType => [lzwme: string, idx: number]

Gets the type of the idx parameter.

1
2
type TestArgsType = Parameters<typeof test>[1];
// TestArgsType => idx: number

Let’s look at the definition of Parameters.

1
type Parameters<T extends (...args: any) => any> = T extends (...args: infer P) => any ? P : never;

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.

1
type TestReturnType = ReturnType<typeof test>;

Let’s look at the definition of ReturnType again.

1
type ReturnType<T extends (...args: any) => any> = T extends (...args: any) => infer R ? R : any;

Very similar to Parameters, except that the return value type of T is obtained and returned via infer R.