Sobes.tech
Junior — Middle

Can you explain the purpose and operation of the 'infer' keyword in TypeScript?

sobes.tech AI

Answer from AI

The infer operator in TypeScript is used within conditional types to extract (infer) a type from another type. It allows you to declare a type variable that will be automatically inferred by the compiler if the type condition is met.

For example, if you have a function type and want to get the type of its argument or return value, you can use infer to extract these types:

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

// Usage example:
type Fn = (x: number) => string;
type Result = ReturnType<Fn>; // Result will be string

Here, infer R tells the compiler: "if the type T matches a function, then infer the return type as R". This is a powerful tool for creating generic and conditional types, allowing for more flexible and dynamic type handling.