BeginnerCoder

Lesson 21 — Conditional types

Types with an if

A conditional type chooses between two types: T extends U ? X : Y reads "if T fits U, then X, else Y". Inside the condition, infer captures a part of the type into a new name — T extends (infer U)[] grabs the item type of an array.

type IsText<T> = T extends string ? "yes" : "no";
type A = IsText<"hi">;  // "yes"
type B = IsText<42>;    // "no"

Why it matters: library types (like the result type of a Promise) are built this way.

Want it another way?
Task

Write Elem<T> (array → item type, otherwise T) and make unwrap return the first item of arrays. Expect 5, then hi.

Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.

Keep going with TypeScript Foundations

Ready for more? Optional paid resources that pick up where this lesson leaves off.

Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.