Open In App

How to use Conditional Types in TypeScript ?

Last Updated : 23 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Javascript




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

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads