Middle
What is the purpose of the 'infer' keyword in TypeScript?
sobes.tech AI
Answer from AI
The infer keyword in TypeScript is used within conditional types to extract (infer) a type from another type. It allows capturing part of a type and using it later.
For example, when working with function types, you can extract the argument type or the return type:
type ReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
// Usage:
type Result = ReturnType<() => string>; // Result will be string
Here, infer R tells the compiler to infer the return type of the function and assign it to the variable R.
Thus, infer helps create more flexible and powerful types that depend on the structure of other types.