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
dateOrNumberOrStringthat is using generic syntax to define a type namedT:-
If the type of
Tis aDate, then the conditional type will return aDatetype. -
If the type of
Tis anumber, then the conditional type will return a type ofDateornumber. -
If the type of
Tis astring, then the conditional type will return aDatetype or anumberor astring. -
If the type of
Tis neither a date nor anumberorstring, the conditional type will returnnever.
-
-
We then define a function named ...