The infer keyword helps TypeScript guess a type inside a conditional type. It makes your types smarter by learning parts of other types automatically.
Inferring types with infer keyword in Typescript
type MyType<T> = T extends SomeType<infer U> ? U : never;The infer keyword can only be used inside a conditional type.
The inferred type U is a new name you give to the part you want to extract.
R from a function type T.type ReturnType<T> = T extends (...args: any[]) => infer R ? R : never;U of elements inside an array type T.type ElementType<T> = T extends (infer U)[] ? U : never;V from a Promise type T.type PromiseValue<T> = T extends Promise<infer V> ? V : never;
This program defines a type GetReturnType that uses infer to find the return type of any function. Then it uses it to get the return type of greet, which is string. Finally, it assigns a string to message and prints it.
type GetReturnType<T> = T extends (...args: any[]) => infer R ? R : never; function greet(name: string): string { return `Hello, ${name}!`; } // Use the type to get the return type of greet type GreetReturn = GetReturnType<typeof greet>; // Example usage: const message: GreetReturn = "Hello, friend!"; console.log(message);
If the type does not match the pattern, the conditional type returns never.
You can only use infer inside the extends part of a conditional type.
Using infer helps create flexible and reusable types that adapt to different inputs.
infer lets TypeScript guess a type inside conditional types.
It is useful to extract parts of complex types like function returns or array elements.
Use it to make your types smarter and more reusable.