20. What are conditional types in TypeScript? How can you use them in your code?

Conditional types in TypeScript allow you to create types that depend on a condition. They are used to select one type based on whether a condition is met. The syntax looks like this:

T extends U ? X : Y

Where T is the type being checked, U is the type to compare against, X is the type returned if the condition is met, and Y is the type returned if the condition is not met.

Example:

type IsString<T> = T extends string ? 'Yes' : 'No'; type Test1 = IsString<'hello'>; // 'Yes' type Test2 = IsString<42>; // 'No'

In this example, if type T is a string, it will return 'Yes', otherwise, it will return 'No'. Conditional types are useful when you want to adjust types based on other types.

devFlipCards 2025

Do you accept cookies?

Cookies are small amounts of data saved locally on you device, which helps our website - it saves your settings like theme or language. It helps in adjusting ads and in traffic analysis. By using this site, you consent cookies usage.