0
0
Typescriptprogramming~3 mins

Why Inferring types with infer keyword in Typescript? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how a tiny keyword can save you hours of guessing and rewriting types!

The Scenario

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.

The Problem

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 Solution

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.

Before vs After
Before
type GetReturnType<T> = T extends (...args: any) => any ? any : never;
After
type GetReturnType<T> = T extends (...args: any) => infer R ? R : never;
What It Enables

It lets you extract and reuse types automatically, making your code smarter and easier to maintain.

Real Life Example

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.

Key Takeaways

Manual type guessing is slow and error-prone.

infer automatically extracts types inside complex structures.

This makes your TypeScript code cleaner and more reliable.