Union Type
PronunciationYOON-yun TYPE
Definition
A union type says a value may be one of several types, for example int | None for a number that can also be missing.
Where you hear it
In TypeScript and Python typing, and in code reviews about functions that may return nothing.
Examples
The function returns
str | None, so check for None before using it.A union of two types is clearer than using the any type.
The parameter accepts an int or a string, and the function handles both.
Common mistake
Using a union and then ignoring the other case. The checker forces you to narrow the type first.
Don't confuse with
A generic type, which keeps one unknown type consistent. A union allows several known alternatives.
Say it at work
- In a meeting or chat
Make the return type a union so callers know it can be empty.
- In an email or ticket
Narrow the union with an if before accessing the field.
Keep exploring
More in Programming Fundamentals