TypeScript · Lesson 15 of 42
Union types: a value that can be one of several types
Learn union types such as string | number, which members you can use before narrowing, and how unions model optional and nullable values.
UNDERSTAND IT. THEN TRY IT.
What you can do after this lesson
You will be able to say "this value is one of these several types", which real data often is. A form field might be a string or empty, an ID might be a number or a string, and a result might be a success or a failure. Unions describe all of these, and they are the foundation for the next three lessons.
The | operator
A union type is written with a vertical bar between types and means "either this or that":
let id: string | number;
id = "A-17";
console.log(id);
id = 17;
console.log(id);A-17
17The variable can hold either kind, one at a time. Anything else is rejected:
let id: string | number;
id = true;example.ts(2,1): error TS2322: Type 'boolean' is not assignable to type 'string | number'.What you can do with a union
Here is the important rule: until you narrow a union, you may only use members that every type in the union has. A number has no toUpperCase, so this fails:
function shout(value: string | number): string {
return value.toUpperCase();
}example.ts(2,16): error TS2339: Property 'toUpperCase' does not exist on type 'string | number'.
Property 'toUpperCase' does not exist on type 'number'.The message explains it in two lines: the property is missing on string | number, because it is missing on number. The fix is to check which type you have, and use only what that type supports. The next lesson, on narrowing, covers the tools for this:
function shout(value: string | number): string {
if (typeof value === "string") {
return value.toUpperCase();
}
return value.toFixed(1);
}
console.log(shout("hello"), shout(42));HELLO 42.0Members shared by all types are always available. Both strings and arrays have length, so a union of the two can use it directly:
function size(value: string | string[]): number {
return value.length;
}
console.log(size("hello"), size(["a", "b"]));5 2Unions of literal types
You met this idea with type aliases. A union of literal types gives a closed set of options:
type Size = "small" | "medium" | "large";
function price(size: Size): number {
if (size === "small") return 3;
if (size === "medium") return 4;
return 5;
}
console.log(price("medium"));4Optional and nullable values
A union with undefined or null describes a value that may be missing. This is the type behind optional properties and functions that sometimes find nothing:
function findUser(id: number): string | undefined {
const users: Record<number, string> = { 1: "Asha", 2: "Ben" };
return users[id];
}
const user = findUser(3);
console.log(user === undefined ? "not found" : user.toUpperCase());not foundWith strict mode, the compiler forces you to check for undefined before using the result. That single rule prevents a huge class of "cannot read properties of undefined" errors.
Array of unions versus union of arrays
These two look similar and mean different things:
const mixed: (string | number)[] = [1, "two", 3];
const onlyStrings: string[] | number[] = ["a", "b"];
console.log(mixed, onlyStrings);[ 1, 'two', 3 ] [ 'a', 'b' ](string | number)[] is one array whose items may each be a string or a number. string[] | number[] is either an array of only strings or an array of only numbers. The parentheses matter, so write them when you mean a mixed array.
Unions in return types
A function can return different types on different paths, and the compiler infers the union. Writing the return type yourself keeps the intent clear:
function parseAge(input: string): number | null {
const age = Number(input);
return Number.isNaN(age) ? null : age;
}
console.log(parseAge("42"), parseAge("forty"));42 nullCallers now know the result may be null, and the compiler makes them handle it.
Common mistakes
Calling a method that only some members have. Narrow first. A union exposes only what all members share.
Forgetting the parentheses in an array of unions. string | number[] means a string or an array of numbers, not an array of mixed items.
Using a union where one precise type will do. If a function always receives a string, do not accept string | undefined just in case.
Ignoring null and undefined. In strict mode they are in the type for a reason; check them before use.
Exercise
Write function formatId(id: string | number): string that returns "ID-" followed by the id, padding numbers to four digits with padStart. Write findIndexOf(items: string[], target: string): number | null that returns null when the item is missing, and use the result safely. Finally, make an array that mixes numbers and strings, and try to call toFixed on its first item to see why narrowing is needed.
Next: Narrowing with typeof, truthiness and equality checks.
KNOWLEDGE CHECK
A quick check. You’ve got this.
Try each question. Every answer comes with an explanation.
Ready for the next small win?
Mark the lesson complete when you are ready.