We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Infer

The infer keyword, when used inside a conditional type, lets us use the type of a value from the true branch. For example:

type GetReturnType<T> = T extends (...args: any[]) => infer R ? R : never;

The GetReturnType is a conditional utility type that extracts the return type of a function type T. We can use it like this:

function greet() { return "Hello, world!"; }
function sum(a: number, b: number) { return a + b; }

type GreetReturnType = GetReturnType<typeof greet>; // string
type SumReturnType = GetReturnType<typeof sum>;     // number

You might be wondering, "Why infer R instead of just R?" Basically "because TypeScript syntax says so". See, this is the type we're trying to "match" in the conditional, because the return value can be anything:

(...args: any[]) => any;

But we can't use any, because we're trying to capture the type in a type variable, so we use R. Buuuuut TypeScript needs to know that R is a type variable, so that's what the infer keyword does. It says "hey, I made this new type variable R, and I want you to remember that in the conditional's return statement, assuming the conditional is true".

The infer keyword goes wherever the unknown type appears in the pattern. In GetReturnType, that unknown type is the function's return type.

Assignment

Support.ai is building a form preview tool. It lets developers generate mock inputs for internal functions – but first, it needs to know what kind of input each function expects.