Conditional Types and Infer 10 exercises
Problem

Distributivity in Conditional Types

In this exercise we're going to examine a little wrinkle in conditional types.

Consider the example below:


type Fruit = "apple" | "banana" | "orange"
type AppleOrBanana = Fruit extends "apple" | "banana" ? Fruit : never
// Fails
type tests = [Expect<Equal<AppleOrBanana, "apple" | "banana"

Loading exercise

Transcript

0:00 In this exercise, we're going to examine a horrible little gotcha with conditional types, and it really extends to this. What we're trying to do is we're saying apple or banana here. We should be able to check, if fruit extends apple or banana, then we return the fruit. Otherwise, we return never.

0:23 know that apple or banana is in here, so we should be able to say apple's in there and banana's in there, so we should return apple or banana, and then we're good to go. This is quite a contrived version of this problem.

0:37 The issue here is something called distributive conditional types. Your job is to look for that in the TypeScript handbook and see if you can work out what's happening here. There are two possible solutions to this problem. Both of them are a little bit tricksy, so good luck.