...

/

Type Inference from Function Signatures and Arrays

Type Inference from Function Signatures and Arrays

Learn TypeScript's type inference for function signatures, arrays, and three standard conditional types: Exclude, Extract, and NonNullable.

In the same way that we can define inferred types based on object properties, we can also infer types based on function signatures.

These inferred types can be inferred from either the function arguments or from the function return type. Let’s take a look at an example of this:

type inferredFromFnParam<T> =
T extends (a: infer U) => void ? U : never;
Function parameter inference

Here, we have a conditional type named inferredFromFnParam, which will infer the type of U from the argument named a of a function signature that has a single parameter, and returns void.

If the function signature does not match what is specified by the extends clause, that is, it does not take a single parameter and does not return void, then the inferred type will be never.

We can use this inferred type as follows:

function testInferredFromFnParam<T>(
arg: inferredFromFnParam<T>
) { }
testInferredFromFnParam<(a: number) => void>(1);
testInferredFromFnParam<(a: string) => void>("test");
Testing inferred types
  • We have a function named testInferredFromFnParam that accepts a single argument of the type that is the result of our conditional inferred type named inferredFromFnParam.

  • We then call this function twice, providing two function signatures with which to compute the conditional inferred type:

    • The call to the testInferredFromFnParam function on line 5 specifies a function signature that accepts a single argument of type number and returns void. Our inferred type, therefore, is the type of the argument named a, which in this case is of type number. Therefore, the testInferredFromFnParam function takes a single ...