Understanding infer in Conditional Types
Extract inner types using infer in extends clauses.
What Is infer?
The infer keyword appears inside conditional types and lets TypeScript capture a type variable from the matched position, so you can use it in the true branch.
type GetReturn<T> = T extends (...args: any[]) => infer R ? R : never;Basic infer Example
Here we extract the return type of any function using infer R.
type ReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
type A = ReturnType<() => string>; // string
type B = ReturnType<() => number[]>; // number[]All lessons in this course
- Understanding infer in Conditional Types
- Building ReturnType and Parameters from Scratch
- Deeply Nested Inference Patterns
- Practical infer Use Cases: Unwrapping Promises