Conditional Types

Writing 'if' statements for your types.

TypeScript5 min readConcept 28 of 54

The Type-Level Ternary

Conditional types allow you to create types that choose one of two possible outputs based on a condition.

They use the exact same ternary syntax as JavaScript (condition ? true_branch : false_branch), but instead of checking runtime values, they check type assignability.

Dynamic Type Utilities

Without conditional types, you have to write a separate type for every possible scenario.

With conditional types, you can write highly dynamic, reusable utility types that automatically adjust their shape based on the type variable passed into them.

Syntax

typescript // If T is a string, return 'yes', otherwise return 'no'. type IsString<T> = T extends string ? "yes" : "no"; type A = IsString<"hello">; // "yes" type B = IsString<42>; // "no" // A more realistic example: // If T is an array, extract its element type. Otherwise, leave it alone. type Flatten<T> = T extends any[] ? T[number] : T; type C = Flatten<string[]>; // string type D = Flatten<number>; // number

Try it

Pass different types into the IsString<T> conditional type evaluator and watch how the ternary logic resolves to the true or false branch.

Pass Type:
type IsString<T> =Textendsstring?"yes":"no";

// Caller
type Res = IsString<"hello">;
Ternary Evaluator
T ="hello"
Evaluating:"hello" extends string?
"yes"

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1What does `type Result = 42 extends number ? true : false` evaluate to?

Remember this

  • Conditional types use the syntax T extends U ? X : Y.
  • The condition T extends U checks if T is assignable to U.
  • When given a union type, conditional types distribute across the union automatically.
  • They are the foundation of advanced TypeScript utility types.

Done with this concept?

Mark it complete to track your progress. No login needed.