← TypeScript Foundations
5 / 25
Lesson 5 — Union types
One of several types
A union type joins types with | and means "any one of these". string | number accepts both text and numbers. It is often used for IDs, which may come from a database as numbers or from a URL as strings.
let answer: boolean | string = true;
answer = "maybe"; // fine
// answer = 3; ← error
Why it matters: real data is not always one type; unions describe that honestly instead of giving up with any.
Want it another way?
Task
Change the type so id can be a number or a string, then set id to "abc" and print it. Expect 42, then abc.
Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.
Test your knowledge
A quick 3-question quiz on this lesson — instant feedback.