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.
We'll cover the following...
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;
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");
-
We have a function named
testInferredFromFnParam
that accepts a single argument of the type that is the result of our conditional inferred type namedinferredFromFnParam
. -
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 typenumber
and returnsvoid
. Our inferred type, therefore, is the type of the argument nameda
, which in this case is of typenumber
. Therefore, thetestInferredFromFnParam
function takes a single ...
-