0
0
Typescriptprogramming~3 mins

Why conditional types are needed in Typescript - The Real Reasons

Choose your learning style9 modes available
The Big Idea

What if your code could think about types and choose the right one all by itself?

The Scenario

Imagine you have a function that should return different types based on the input type, and you try to write separate versions for each case manually.

For example, if you pass a string, it returns a number; if you pass a number, it returns a string.

The Problem

Writing separate functions or many type checks for each input type quickly becomes messy and hard to maintain.

It's easy to make mistakes, and the code grows longer and confusing.

The Solution

Conditional types let you write one smart type that automatically picks the right output type based on the input type.

This keeps your code clean, safe, and easy to understand.

Before vs After
Before
function process(input: string): number { /*...*/ }
function process(input: number): string { /*...*/ }
After
type Process<T> = T extends string ? number : string;
function process<T>(input: T): Process<T> { /*...*/ }
What It Enables

It enables writing flexible, type-safe code that adapts automatically to different input types without repeating yourself.

Real Life Example

Think of a function that parses user input: if given a JSON string, it returns an object; if given an object, it returns a JSON string.

Key Takeaways

Manual type handling is repetitive and error-prone.

Conditional types automate type decisions based on input.

This leads to cleaner, safer, and more maintainable code.