Course contentsShow
← TypeScript
Lesson 767 of 1,79618. Conditional TypesFree lesson

Your First Conditional Type

Write a simple conditional type that returns different types based on a condition, like IsString<T>.

Your First Conditional Type

What you'll learn: How to write a simple conditional type that returns different types based on a condition.


The Core Idea

Think of conditional types like an if-else statement, but for types instead of values. Just as you'd write typeof x === 'string' ? 'yes' : 'no' to check a value at runtime, you can write T extends string ? 'yes' : 'no' to check a type at compile time.

The syntax looks like this:

T extends U ? TrueType : FalseType

If type T can be assigned to type U, you get TrueType. Otherwise, you get FalseType.

A Simple Example: IsString

Let's create a conditional type that checks whether a given type is a string:

type IsString<T> = T extends string ? true : false;

Now when you use it:

type A = IsString<string>;        // true
type B = IsString<number>;        // false
type C = IsString<'hello'>;       // true (string literals extend string)
type D = IsString<boolean>;       // false

Notice how the same type definition produces different results depending on what type argument you pass in. That's the power of conditional types — they branch based on type relationships.

Why This Matters

Before conditional types, TypeScript couldn't make decisions about types dynamically. Now you can create types that adapt based on their inputs, enabling sophisticated type transformations and type-level logic.

Key Takeaway: Conditional types use T extends U ? X : Y syntax to return different types based on whether one type can be assigned to another, enabling type-level branching logic.