Junior — Middle
What is the role of the Infer operator in the context of types and how is it applied?
sobes.tech AI
Answer from AI
The infer operator is used in TypeScript (often in Node.js projects with typing) within conditional types to extract a type from another type. It allows declaring a temporary type variable that can be used within the conditional type.
Example of usage:
Type ReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
function foo() { return 42; }
Type FooReturn = ReturnType<typeof foo>; // FooReturn will be number
Here, infer R allows extracting the return type of the function T. If T is a function, then R is its return type; otherwise, never.
Thus, the infer operator helps create more flexible and generic types by extracting internal types from complex structures.