

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Still calibrating
click for more info
Not enough gems
Cost: 6 gems
1: Conditional Types
incomplete
2: Infer
incomplete
3: Mapped Types
incomplete
4: Mapped Types With Conditionals
incomplete
5: Extracting Keys from Types
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
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.
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.