Put the TypeScript enums and Booleans away
Blog post from LogRocket
The author shares their experience with TypeScript enums and discriminated unions, initially appreciating enums for their ability to prevent string typo errors in Redux actions by providing a set of named constants. However, they discovered the limitations of enums when modeling complex states, such as those in an authentication workflow, leading to the adoption of discriminated unions, also known as algebraic data types. These unions, by utilizing a kind field as a discriminator, enable more precise type narrowing, ensuring only relevant data is accessed in each state. This approach not only offers executable documentation but also improves code reliability by aligning with the compiler's ability to enforce correctness, unlike Boolean-based state modeling, which can lead to logical contradictions. The author highlights the utility of discriminated unions in keeping coding practices disciplined, especially in the flexible environment of JavaScript programming, while mentioning tools like LogRocket that enhance understanding of user interactions in web and mobile applications.