Type System
TS Conditional Types
Using Conditional Types
TypeScript conditional types infer types based on conditions using extends.
Introduction to Conditional Types
Conditional types in TypeScript provide a powerful way to choose one type over another based on a condition. They are a form of generic type that uses the extends
keyword to determine which type to return. Conditional types enable you to create flexible and reusable type definitions that adapt based on input types.
Basic Syntax of Conditional Types
The syntax of a conditional type is similar to an if-else
statement but for types. Here's a basic structure:
In this syntax, if type T
extends type U
, then the type resolves to X
. Otherwise, it resolves to Y
. This is particularly useful for type transformations and conditional logic in your TypeScript code.
Example: Conditional Type for Function Return
Consider a scenario where you want to define a type that returns a specific function type based on a condition. For example, if the input is a string, the function should return a string, and if it's a number, it should return a number.
In this example, the ReturnType
type conditionally defines a function return type based on whether the input type is a string
or not.
Using Conditional Types with Generics
Conditional types become even more powerful when used with generics. They allow you to create types that are highly adaptable and can change their shape based on the input types.
In this example, the processValue
function uses a conditional type to determine its return type, which adapts based on the input type.
Distributive Conditional Types
TypeScript's conditional types are distributive when applied to union types. This means the conditional type is applied to each member of the union individually, and the results are combined back into a union.
Here, ToArray
turns a union type into a union of arrays. This distributive nature enables complex type transformations.
Conclusion
Conditional types in TypeScript offer a versatile and powerful way to create complex type logic. By leveraging the extends
keyword, developers can build types that dynamically adapt to different scenarios, improving both code flexibility and type safety.
Type System
- Previous
- Literal Types
- Next
- Mapped Types