Distributed Conditional Types and the Conditional Type Inference
Explore how to use distributed conditional types in TypeScript to allow multiple type returns based on conditions. Understand conditional type inference to derive new types dynamically from object properties, enhancing type flexibility and safety in your code.
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:
-
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 ...