Distributivity in Conditional Types in TypeScript

There’s one very important gotcha with Conditional Types in TypeScript that catches almost everyone at some point. It’s called 'Distributivity.' At first, conditional types feel predictable. You write a condition. TypeScript checks it. You get a result. But when union types enter the picture, things suddenly behave very differently. The core idea that you need to understand is - Conditional types distribute over union types, but only in very specific situations. So, what does 'distribute' actually mean? When a conditional type is written using a generic type parameter, and that parameter is later given a union, TypeScript doesn’t check the union as a whole. Instead, it applies the condition to each member of the union individually, and then unions the results back together. This behavior is extremely powerful, but also very easy to misunderstand if you don’t know it exists. Now here’s the subtle part that causes confusion. Distributivity only happens when the conditional type is applied to a generic type parameter. If you write a conditional type directly against a union type, TypeScript does not distribute. In that case, TypeScript checks the union as a single unit. And if any member of that union fails the condition, the entire check fails. That’s why two conditional types that look almost identical can produce completely different results. One distributes. The other doesn’t. This distinction explains a lot of "why did this become 'never'?" moments when working with conditional types. There’s also an important escape hatch. If you don’t want distributive behavior, you can explicitly turn it off by wrapping the type in a tuple. This tells TypeScript: 'Treat this as one thing, not a union of things.' And interestingly, you can also force distribution in situations where you’re not using a type parameter, by introducing one via 'infer.' At that point, TypeScript is back in a generic context, and distributivity kicks in again. The key takeaway is that Conditional types don’t behave differently by accident. They behave differently based on how you write them. Once you understand when distributivity applies, and when it doesn’t, a lot of confusing behavior suddenly becomes predictable. #TypeScript #JavaScript #Programming #Coding #WebDevelopment

  • text

To view or add a comment, sign in

Explore content categories