Skip to content

Use Type Narrowing

Follow the “TypeScript Narrowing” pattern

TypeScript Narrowing is a type-safety code pattern in JavaScript that allows you to narrow down the type of a variable based on a condition. This is useful when you have a variable that can be of multiple types and you want to ensure that it is of a specific type before you use it (for example, when you’re working with generics or union types).

Another name for this code pattern is “type guards”.

Here’s an example of how you can use TypeScript Narrowing to ensure that a variable is of a specific type before you use it:

if (typeof filterQuery !== "string") {
return res.status(400).send("Bad input detected!");
}

However, if you follow this type-safety code pattern you may end up with a lot of boilerplate code that is hard to maintain. In fact, this is what TypeScript wanted to solve to begin with. And so, consider the following disadvantages before you start employing type guards all over your codebase:

  • 🚧 you need to remember adding these type guards all the time
  • 🚧 your codebase might feel more “dirty” with all these type checks
  • 🚧 not all type guards are created equal (e.g: typeof null is… `object 😅)