Search⌘ K

Distributed Conditional Types and the Conditional Type Inference

Learn about distributed conditional types and how to use them in TypeScript to derive multiple types or infer a new type based on a condition.

Distributed conditional types

When defining conditional types, instead of returning only a single type as part of our conditional statements, we can also return a number of types or distributed conditional types. As an example of this, consider the following code:

TypeScript 4.9.5
// This is a generic type that takes a type parameter T and returns a union type of Date, number, or string, depending on the type of T.
type dateOrNumberOrString<T> =
T extends Date ? Date :
T extends number ? Date | number :
T extends string ? Date | number | string :
never;
function compareValues
<T extends string | number | Date | boolean>
(
input: T,
compareTo: dateOrNumberOrString<T>
) {
// do comparison
}
Returning multiple types
  • We have a conditional type named dateOrNumberOrString that is using generic syntax to define a type named T:

    • If the type of T is a Date, then the conditional type will return a Date type.

    • If the type of T is a number, then the conditional type will return a type of Date or number.

    • If the type of T is a string, then the conditional type will return a Date type or a number or a string.

    • If the type of T is neither a date nor a number or string, the conditional type will return never.

  • We then define a function named ...