Overview - Union type syntax and behavior
What is it?
Union types in TypeScript allow a variable to hold more than one type of value. You write them by joining types with a vertical bar (|), like string | number. This means the variable can be either a string or a number, giving flexibility while still checking types. It helps catch errors before running the code.
Why it matters
Without union types, you would have to choose only one type for a variable or use very loose types that don't check well. This can cause bugs when unexpected types appear. Union types let you write safer code that still handles different kinds of data, making programs more reliable and easier to maintain.
Where it fits
Before learning union types, you should understand basic TypeScript types like string, number, and boolean. After union types, you can learn about intersection types, type guards, and advanced type narrowing to handle complex data safely.