Building React Components Using Unions in TypeScript

Update October 4th, 2023: Added an additional explanation on how you can more easily create Unions making them more readable, and compared them to other languages.

The common theme in a lot of React examples utilizes 2 types of data to build React components around: primitives and Objects. In this article, we’re going to talk about a 3rd called Discriminated Unions. We’ll go over what problems they solve, what their future looks like in JavaScript and possibly TypeScript, and what libraries can help you now.

Unions in TypeScript can help prevent a lot of common bugs from happening so they’re worth using, especially for UI developers where we have to visualize complicated data. While Unions help narrow what you have to draw, they also expose edge cases that your UI Designer/Product Owner may not have accounted for in their visual design. In JavaScript this would be a blank screen, a null pointer, or an error boundary that you’re confused about. Most importantly, they can help you make impossible situations impossible.

Continue reading “Building React Components Using Unions in TypeScript”