0
0
Typescriptprogramming~3 mins

Why Non-distributive conditional types in Typescript? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could tell TypeScript to treat a group of types as one, avoiding confusing splits and mistakes?

The Scenario

Imagine you have a list of different fruits and you want to check if each fruit is an apple or not. Doing this by hand means checking each fruit one by one and writing separate code for each case.

The Problem

Manually checking each item is slow and easy to mess up. If the list grows or changes, you have to rewrite or copy-paste code many times, which leads to mistakes and wasted time.

The Solution

Non-distributive conditional types let you write one smart rule that applies to the whole list at once, without splitting it up. This saves time and keeps your code clean and easy to change.

Before vs After
Before
type Check<T> = T extends 'apple' ? 'Yes' : 'No';
type Result = Check<'apple' | 'banana'>; // 'Yes' | 'No' (distributes)
After
type Check<T> = [T] extends ['apple'] ? 'Yes' : 'No';
type Result = Check<'apple' | 'banana'>; // 'No' (no distribution)
What It Enables

This concept lets you control how TypeScript checks types, making your code smarter and more precise when working with groups of types.

Real Life Example

When building a form that accepts different input types, you can use non-distributive conditional types to apply validation rules to the entire input type at once, instead of handling each input type separately.

Key Takeaways

Manual checks for each type are slow and error-prone.

Non-distributive conditional types apply conditions to whole types without splitting.

This leads to cleaner, safer, and easier-to-maintain code.