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.
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.
A quick 3-question quiz on this lesson — instant feedback.
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.
Project-based TypeScript Foundations courses if you want a structured paid path after the free lessons. Wait for a sale — prices drop often.
Browse on Udemy →Search Amazon for TypeScript Foundations books — check the publication year so the examples match current versions.
Search Amazon →