A TypeScript union type permits a value to have any one of several specified types. Join the types with `|`: `number | string` accepts either a number or a string. Use a union when both are intentional, rather than using `any` and giving up type checks. The annotation guides the compiler; it does not change JavaScript’s runtime behavior. section 3.4.2
Accepting two parameter types
In `function myFunction(param: number | string)`, calls with `1` and `"London"` are both permitted. But `param.toFixed(2)` is not permitted without a check: strings do not provide that method. Check `typeof param == "number"` first, then call `toFixed` in the number branch. The compiler can treat the value as a number there. section 3.4.2
A union does not make every operation valid for every member. Even `param + 100` produces a compiler error for `number | string` in the example because the operation is ambiguous to the compiler. Casting `param as any` permits it, but bypasses that check; checking the type keeps the distinction explicit. section 3.4.2
Include `undefined` or `null` when those values are allowed: `let place: string | undefined | null` permits all three possibilities. They cannot be assigned to a variable whose type excludes them. Before using a member’s methods, guard against the missing values. For `number | undefined | null`, `count?.toFixed(2)` instead skips the call when `count` is null or undefined, yielding a `string | undefined` result. section 3.4.5 section 3.4.7
An optional parameter and a union parameter are not interchangeable. `val?: string` allows the caller to omit the argument and has type `string | undefined` inside the function. `val: string | undefined` still requires an argument, even if that argument is `undefined`. section 4.2.1
Restricting mixed array elements
`let values: (number | string | boolean)[] = [100, "Adam", true]` permits those three element types. Parentheses matter: `number | string | boolean[]` instead describes a number, a string, or an array of booleans. Reading an element gives a union type; assigning a new element is checked against the allowed types. section 4.3 section 4.3.1









