Union types and narrowing
A union type means "one of these types", written with |:
let id: string | number;
id = 42; // fine
id = "A-42"; // fine
id = true; // error
With a union, TypeScript only lets you do what is safe for every member:
function show(id: string | number) {
return id.toUpperCase();
// error: toUpperCase does not exist on type 'number'
}
Narrowing
When you check the type, TypeScript narrows it inside that branch:
function show(id: string | number): string {
if (typeof id === "number") {
return id.toFixed(0); // here id is a number
}
return id.toUpperCase(); // here id must be a string
}
Ways to narrow:
| Check | Narrows to |
|---|---|
typeof x === "string" |
string (also "number", "boolean") |
Array.isArray(x) |
an array |
x === null, x !== undefined |
removes null / undefined |
if (x) |
removes null, undefined, and other "empty" values |
null and undefined
With strict checking (used here), null is its own type. A value that might be missing is written string | null, and TypeScript makes you handle the missing case before using it.
Your task
normalizeId(id: string | number): string: numbers become 6 digits with leading zeros (42gives"000042"); strings are trimmed and upper-cased.countItems(x: string | string[] | null): number:nullis 0, a list is its length, a single string is 1.