Union Types and Type Guards
Explore how to apply union types and type guards in TypeScript to improve code reliability. Understand the use of typeof, instanceof, in operator, and custom type guard functions to safely narrow types and manage complex type unions in your code.
We'll cover the following...
Type guards
TypeScript calls the functionality that lets TypeScript know it can use a specific type, called a type guard. A type guard is a block of code in which we narrow the definition of a union type to the extent that TypeScript can infer the narrower type and use that information to type check the code.
For example, one use of a union type is to allow our method to take in multiple different types of arguments, so we might have a method like this:
const logAThing(log: number | string | boolean | symbol) {
}
We want to treat the log argument differently based on its type, which likely involves calling methods that only make sense for the actual type of the argument, not the union type. We therefore want to have a type guard based on the type. How we create a type ...