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.
We'll cover the following...
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:
// 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}
-
We have a conditional type named
dateOrNumberOrString
that is using generic syntax to define a type namedT
:-
If the type of
T
is aDate
, then the conditional type will return aDate
type. -
If the type of
T
is anumber
, then the conditional type will return a type ofDate
ornumber
. -
If the type of
T
is astring
, then the conditional type will return aDate
type or anumber
or astring
. -
If the type of
T
is neither a date nor anumber
orstring
, the conditional type will returnnever
.
-
-
We then define a function named ...