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
  1. 1
    When compiling TypeScript code to JavaScript, the compiler will throw any errors related to variable types. This process of compilation involves giving the TypeScript compiler the information it ne…
  2. 2
    One way that TypeScript can narrow a type is with a conditional statement that checks if a variable is a specific type. This pattern is called a type guard. Type guards can use a variety of opera…
  3. 3
    As we write more types, we’re bound to create custom types to better describe our data’s properties and methods. While using typeof can get us pretty far, sometimes we want to see if a specific met…
  4. 4
    In our previous examples, we’ve used two separate if statements as type guards to handle each possible type. It turns out that TypeScript can recognize the else block of an if/else statement as bei…
  5. 5
    TypeScript’s ability to infer types after a type guard stretches even further than inferring the type within an else statement. TypeScript can also type narrow without an else statement, provided t…
  6. 6
    You’re the type of person that finishes lessons! Nice work on completing Type Narrowing. You’re now equipped to utilize TypeScript’s powers of inference through type guards and type narrowing. Le…

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