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.