Conditional types in TypeScript are a powerful feature that allows developers to create types based on conditions. They enable more dynamic and flexible type definitions, which can lead to more robust and maintainable code. The syntax for a conditional type is straightforward and follows the pattern: `T extends U ? X : Y`, where `T` is the type being checked, `U` is the type being compared against, `X` is the type returned if the condition is true, and `Y` is the type returned if the condition is false.
Conditional types can be particularly useful when working with generics. They allow you to create types that adapt based on the input types provided. For example, you can create a type that returns a different type based on whether the input is a string or a number.
type IsString = T extends string ? "Yes" : "No";
In this example, `IsString` checks if the type `T` extends `string`. If it does, it returns the string literal type "Yes"; otherwise, it returns "No".
type ExtractString = T extends string ? T : never;
type MixedTypes = string | number | boolean;
type OnlyStrings = ExtractString; // Result: string
In this example, `OnlyStrings` will be of type `string`, as it filters out the non-string types from the union.
type DefaultType = T extends string ? T : string;
type Test1 = DefaultType; // Result: string
type Test2 = DefaultType; // Result: string
Here, `DefaultType` will default to `string` if no type is provided, demonstrating how conditional types can simplify type definitions.
In conclusion, conditional types using `extends` in TypeScript provide a powerful way to create dynamic types based on conditions. By understanding their syntax and practical applications, developers can leverage this feature to enhance type safety and code maintainability.