Discover how a tiny keyword can save you hours of guessing and rewriting types!
Why Inferring types with infer keyword in Typescript? - Purpose & Use Cases
Imagine you have a big box of mixed toys and you want to sort them by type manually every time you open the box.
You have to look at each toy, guess its type, and write down what it is before you can play with it.
This manual sorting is slow and tiring.
You might make mistakes guessing the toy types, and every time you get new toys, you have to start over.
It’s easy to get confused and waste time.
The infer keyword in TypeScript acts like a smart helper that looks inside your box and figures out the toy types automatically.
It saves you from guessing and writing extra code.
You get the exact type information without the hassle.
type GetReturnType<T> = T extends (...args: any) => any ? any : never;
type GetReturnType<T> = T extends (...args: any) => infer R ? R : never;
It lets you extract and reuse types automatically, making your code smarter and easier to maintain.
When you write a function that returns different shapes of data, infer helps you capture the exact return type so you can use it safely elsewhere without repeating yourself.
Manual type guessing is slow and error-prone.
infer automatically extracts types inside complex structures.
This makes your TypeScript code cleaner and more reliable.