Unlocking the Power of TypeScript Enums and Unions
As I ventured into the world of TypeScript, I was thrilled to discover the enum feature, which brought back fond memories of my C# days. Enums are essentially sets of named constants that can take either numeric or string forms. In this article, we’ll explore how enums can be misused and how TypeScript’s discriminated unions can revolutionize your coding experience.
The Lure of Enums
At first, I used enums everywhere, from Redux actions to finite state machines. My motivation was to avoid pesky string typo errors, and enums seemed like the perfect solution. However, as I delved deeper, I realized that I was missing out on one of TypeScript’s most exceptional features.
The Limitations of Enums
Take, for instance, an AuthenticationStates enum that models an authentication workflow. While enums ensure that a user can’t be in multiple contradictory states at once, they fall short when it comes to handling additional data, such as error objects. I initially attempted to address this by adding fields to each authentication state, but this approach led to repetitive code and potential bugs.
Enter Discriminated Unions
That’s when I discovered discriminated unions, also known as algebraic data types. These powerful constructs allow us to create unions that can be composed of many types, not just primitive ones. By introducing a discriminator field, we can create a union that only requires the same kind field as each element in the union.
Type Narrowing and Compiler Enforcement
The true magic happens when TypeScript type narrows on a discriminator of a union. This means that only the appropriate data is available on each type, ensuring that we can’t access an authToken if we’re not in the AUTHENTICATED state. The compiler enforces this correctness, making it impossible to access incorrect data.
Booleans Don’t Cut It
Attempts to model state with Booleans inevitably lead to a mess of tangled logic and contradicting variables. Algebraic data types, on the other hand, provide a elegant solution to this problem.
Unions: The Ultimate Executable Documentation
Discriminated unions serve as beautiful, executable documentation that keeps developers on the right track. They’ve been around in functional languages like Haskell, and it’s exciting to see TypeScript bring them to the frontend development community.
LogRocket: Your Partner in Frontend Development
LogRocket is a powerful frontend application monitoring solution that lets you replay problems as if they happened in your own browser. With its ability to log Redux actions and state, console logs, JavaScript errors, and more, LogRocket is the perfect companion for your TypeScript journey. Try it for free today!