Skip to content

Instantly share code, notes, and snippets.

@danieldietrich
Last active September 27, 2022 20:20
Show Gist options
  • Save danieldietrich/c0a21d28a52b05f307e4a456533de287 to your computer and use it in GitHub Desktop.
Save danieldietrich/c0a21d28a52b05f307e4a456533de287 to your computer and use it in GitHub Desktop.
TypeScript: Conditional types are distributive over type parameters.

Def. A conditional type with a checked naked type parameter T is called distributive conditional types.

Example:

// given U, X and Y
type DistributiveConditionalType<T> = T extends U ? X : Y;

Distributive conditional types are automatically distributed over union types during instantiation.

Example:

  DistributiveConditionalType<A | B | C>
= (A | B | C) extends U ? X : Y
= (A extends U ? X : Y) | (B extends U ? X : Y) | (C extends U ? X : Y)

Given

type DistributiveConditionalType<T1, T2> = T1 extends T2 ? true : false;

Then

  DistributiveConditionalType<never, 1> // why resolved as πŸ‘‰ never?
= (never) extends (1) ? true : false    // why resolved as πŸ‘‰ true?
= ??? // How does the πŸ‘‰ distribution look like?

βœ… Solved distribution:

  DistributiveConditionalType<never, 1>
= never // never is the empty union, it distributes to nothing and therefore the type resolves to never

βœ… Solved the expanded type:

  (never) extends (1) ? true : false
= true // no type extends anything by definition
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment