Chapter 7. TypeScript Recipes
As the TypeScript community has grown, developers have come up with more and more tricks for solving specific problems. Some of these “recipes” leverage TypeScript’s type checker to catch new categories of mistakes, such as values getting out of sync or nonexhaustive conditionals. Others are tricks for modeling patterns that TypeScript struggles with on its own: iterating over objects, filtering null
values from Arrays, or modeling variadic functions.
By applying the recipes in this chapter, you’ll help TypeScript catch more real problems with fewer false positives. If you enjoy these, you’ll find many more recipes in Stefan Baumgartner’s TypeScript Cookbook.
Item 59: Use Never Types to Perform Exhaustiveness Checking
Static type analysis is a great way to find places where you do something that you shouldn’t. When you assign the wrong type of value, reference a nonexistent property, or call a function with the wrong number of arguments, you’ll get a type error.
But there are also errors of omission: times when you should do something but you don’t. While TypeScript won’t always catch these on its own, there’s a popular trick that can be used to convert a missing case in a switch
or if
statement into a type error. This is known as “exhaustiveness checking.” Let’s see how it works.
Suppose you’re building a drawing program, perhaps using the HTML <canvas>
element. You might define the set of shapes you can draw using a tagged union:
type
Coord
=
Get Effective TypeScript, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.