Type Narrowing
Leverage TypeScript’s type system to gain insights into the runtime behavior of your code by narrowing down what union types.
StartKey Concepts
Review core concepts you need to learn to master this subject
TypeScript Union Type Narrowing
TypeScript Type Guard
TypeScript Type Guard Accepted Types with typeof
TypeScript Type Guard with in
operator
TypeScript Type Guard if-else
Statement
TypeScript Type Guard if
Statement Function Return
TypeScript Union Type Narrowing
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.
- 1When 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…
- 2One 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…
- 3As 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…
- 4In 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…
- 5TypeScript’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…
- 6You’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
How you'll master it
Stress-test your knowledge with quizzes that help commit syntax to memory