0
0
Typescriptprogramming~3 mins

How TypeScript infers generic types - Why You Should Know This

Choose your learning style9 modes available
The Big Idea

What if your code could guess the right types for you, saving time and mistakes?

The Scenario

Imagine you have a function that works with different types of data, like numbers or strings, and you have to write separate versions for each type manually.

For example, one function for numbers, another for strings, and so on.

The Problem

This manual approach is slow and repetitive.

Every time you want to support a new type, you write more code, increasing chances of mistakes and making your program harder to maintain.

The Solution

TypeScript's generic type inference automatically figures out the types you use when calling a function.

This means you write one flexible function, and TypeScript fills in the correct types for you behind the scenes.

Before vs After
Before
function identityNumber(value: number): number { return value; }
function identityString(value: string): string { return value; }
After
function identity<T>(value: T): T { return value; }
const num = identity(123);
const str = identity('hello');
What It Enables

This lets you write reusable, type-safe code that adapts automatically to different data types without extra work.

Real Life Example

Think of a function that returns the first item of any list, whether it's a list of names, numbers, or dates, without rewriting it for each type.

Key Takeaways

Manual type-specific functions are repetitive and error-prone.

TypeScript infers generic types to simplify and secure your code.

You write one function that works for many types automatically.