What if you could tell TypeScript to treat a group of types as one, avoiding confusing splits and mistakes?
Why Non-distributive conditional types in Typescript? - Purpose & Use Cases
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.
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.
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.
type Check<T> = T extends 'apple' ? 'Yes' : 'No'; type Result = Check<'apple' | 'banana'>; // 'Yes' | 'No' (distributes)
type Check<T> = [T] extends ['apple'] ? 'Yes' : 'No'; type Result = Check<'apple' | 'banana'>; // 'No' (no distribution)
This concept lets you control how TypeScript checks types, making your code smarter and more precise when working with groups of types.
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.
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.