25. What is the purpose of infer in TypeScript, and how is it used in advanced type manipulation?

infer is a keyword in TypeScript used in the context of conditional types. It allows you to extract a type from a given expression when the condition is met. It is mainly used in advanced type manipulation, such as extracting types from functions, arrays, or objects.

Example of using infer:

type ReturnType<T> = T extends (...args: any[]) => infer R ? R : never; function add(a: number, b: number): number { return a + b; } type AddReturnType = ReturnType<typeof add>; // 'number'

In this example, infer allows us to extract the return type of a function (in this case, number). Using infer in conditional types enables flexible manipulation of types at the syntactical level, allowing for the creation of more advanced and dynamic types.

devFlipCards 2025

Do you accept cookies?

Cookies are small amounts of data saved locally on you device, which helps our website - it saves your settings like theme or language. It helps in adjusting ads and in traffic analysis. By using this site, you consent cookies usage.