Key Concepts

Review core concepts you need to learn to master this subject

TypeScript Union Type Narrowing

const choices: [string, string] = ['NO', 'YES']; const processAnswer = (answer: number | boolean) => { if (typeof answer === 'number') { console.log(choices[answer]); } else if (typeof answer === 'boolean') { if (answer) { console.log(choices[1]); } else { console.log(choices[0]); } } } processAnswer(true); // Prints "YES" processAnswer(0); // Prints "NO"

Since a variable of a union type can assume one of several different types, you can help TypeScript infer the correct variable type using type narrowing. To narrow a variable to a specific type, implement a type guard. Use the typeof operator with the variable name and compare it with the type you expect for the variable.

Type Narrowing
Lesson 1 of 1

What you'll create

Portfolio projects that showcase your new skills

Pro Logo

How you'll master it

Stress-test your knowledge with quizzes that help commit syntax to memory

Pro Logo