Sobes.tech
Middle+

What is the purpose of 'infer' in TypeScript?

sobes.tech AI

Answer from AI

In TypeScript, the keyword infer is used within conditional types to extract (infer) a type from another type. It allows capturing part of a type and using it later.

Example of using infer:

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

// Here we check if T is a function, and if so, extract the return type R

function example(): string {
  return "hello";
}

 type Result = ReturnType<typeof example>; // Result will be string

infer is useful for creating generic utility types that can extract information from complex types, such as function parameters, array element types, promise types, etc.

Thus, infer extends the capabilities of the TypeScript type system, allowing for more flexible and powerful types.

What is the purpose of 'infer' in TypeScript… - sobes.tech