Discriminated Unions in Practice
Explore the use of discriminated unions in TypeScript, including string, number, boolean literals, and enums as discriminators. Understand how to model complex domains and business rules precisely by composing union types, and learn how these concepts align with algebraic data types. Practice creating types that simulate real-world scenarios with multiple discriminators.
We'll cover the following...
Non-string discriminators
In the example from the previous lesson, we used a string literal property called type as a discriminator. First, the discriminator doesn’t have to be called "type". Any property name will be fine.
Second, the discriminator doesn’t have to be a string. You can also use number literals, Boolean literals, or even enums!
The built-in IteratorResult type in TypeScript (starting from version 3.6) ...