What if you could write one rule that magically applies to every type in a list without extra work?
Why Distributive conditional types in Typescript? - Purpose & Use Cases
Imagine you have a list of different fruit types, and you want to check each one to see if it is a citrus fruit or not. Doing this by hand means writing separate checks for each fruit, which quickly becomes messy and repetitive.
Manually checking each type is slow and error-prone. If you add more fruit types, you must update your checks everywhere. It's easy to forget one or make mistakes, leading to bugs and wasted time.
Distributive conditional types let TypeScript automatically apply a condition to each type in a union. This means you write the rule once, and TypeScript handles the rest, making your code cleaner and safer.
type CheckFruit<T> = T extends 'orange' ? 'citrus' : T extends 'lemon' ? 'citrus' : 'other';
type CheckFruit<T> = T extends 'orange' | 'lemon' ? 'citrus' : 'other';
This lets you write flexible, reusable type rules that automatically adapt to each member of a union, saving time and reducing bugs.
When building a form library, you can create a type that checks each input field type and assigns validation rules automatically, no matter how many field types you add later.
Manual type checks get complicated and error-prone with many types.
Distributive conditional types apply conditions automatically to each union member.
This makes your TypeScript code cleaner, safer, and easier to maintain.