Open In App

How to use Conditional Types in TypeScript ?

The conditional types in TypeScript are created using a condition that will only be created based on the condition check and its return value. They implement the extends keyword to check the condition and create a type based on the returned true or false value. The conditional types are mainly used to create flexible and generic type definitions. It enhances the code readability and maintainability by creating dynamic types based on the runtime conditions.

Syntax:

type typeName<T> = T extends type ? statement1: statement2;

Example: The below code example will explain how you can use the conditional types in TypeScript.




type myType<T> =
    T extends number ? number : any;
 
const var1: myType<string> =
    "GeeksforGeeks";
const var2: myType<number> = 2009;
 
console.log(var1, var2);

Output:

GeeksforGeeks 2009
Article Tags :