As developers, we often face scenarios where a variable or a function parameter could legitimately hold more than one type of value. Maybe an ID can be a number or a string, or a function can accept different but related object shapes. In vanilla JavaScript, we’d handle this with runtime checks, but in TypeScript, we can achieve this with full type safety using Union Types.
Let’s dive into what union types are, how to use them, and the powerful patterns they enable.
What are Union Types?
A union type allows you to define a type that can be one of several possible types. You create a union type by using the pipe (|) symbol between the types.
Think of it as an “OR” for types. A variable of type string | number can hold a value that is either a string or a number.
Continue reading Mastering TypeScript Union Types: A Practical Guide