Another cool trick in TypeScript is to use Discriminated Unions. Discriminated unions are a way to create a type that is a union of multiple types, where each type has a unique property (called a “discriminant”) that can be used to distinguish between them. This makes it easier to handle different types in a type-safe manner.
Let’s take a look at an example:
Suppose you are building a messaging app that supports different types of messages: text, image, and video. You can create separate types for each message type and use a discriminant property called type
:
|
|
Now, you can create a Message
type as a discriminated union of these message types:
|
|
This Message
type can represent any of the three message types. You can handle different message types using a type-safe switch statement based on the type
property:
|
|
TypeScript will infer the correct type within each case block, ensuring that you are using the correct properties for each message type.
Here’s how you can use the handleMessage
function with different message types:
|
|
Discriminated Unions help you create more versatile and maintainable TypeScript code by allowing you to work with different types in a type-safe manner. This can help you catch errors early in the development process and make your code easier to understand and modify.
Cheer! 🍺