A user code may be text like "U-001", or a number like 42. A coffee size may only be "small", "medium" or "large". A plain string can't express either rule. For the user code, string is too narrow, because a number can't go in. For the coffee size, string is too loose, because any text can go in.
A union type handles the first rule: a value may be one of several types, and string | number reads "string or number". A literal type handles the second rule: a type that holds exactly one value, like "small". When you join a few literals, you get a fixed list of choices. Picture the size buttons on a coffee shop's cash register: small, medium, large. The cashier can't enter a "jumbo" order, because there's simply no button for it. Each button is one literal type, and the row of buttons is the join of those literals.
Union: one of several types
The variable code below may hold a string or a number:
let code: string | number = "abc";
code = 42; // allowed
code = true; // error
string | numberis a union: several types joined by the|sign (pipe). The value may be a string, or a number. Each type inside a union is called a member.code = trueis rejected:Type 'boolean' is not assignable to type 'string | number'.(ts(2322)), because boolean isn't on the list.
With a union value, you may only do what can be done to every member. toUpperCase() only exists on strings, so this code is rejected:
function formatId(id: string | number): string {
return id.toUpperCase(); // error
}
The message: Property 'toUpperCase' does not exist on type 'string | number'. (ts(2339)). TypeScript doesn't know whether id is a string or a number, so you have to check first. Use typeof from JavaScript. Inside an if that checks typeof id === "string", TypeScript knows id must be a string:
function formatId(id: string | number): string {
if (typeof id === "string") {
return id; // here id: string
}
return "ID-" + id; // here id: number
}
console.log(formatId("abc")); // abc
console.log(formatId(42)); // ID-42
This table shows which branch runs for each call:
| Call | typeof id |
Branch that runs | Result |
|---|---|---|---|
formatId("abc") |
"string" |
return id |
"abc" |
formatId(42) |
"number" |
return "ID-" + id |
"ID-42" |
The union you will meet most often is string | null: a string, or empty on purpose. It must be checked first too:
function title(message: string | null): string {
return message.toUpperCase(); // error
}
The message: 'message' is possibly 'null'. (ts(18047)). It means: message may be null. Here are two ways to handle null, in title and in greet:
function title(message: string | null): string {
if (message === null) {
return "(empty)";
}
return message.toUpperCase(); // here message: string
}
function greet(name: string | null): string {
return "Hello, " + (name ?? "Guest");
}
console.log(title(null)); // (empty)
console.log(title("promo")); // PROMO
console.log(greet(null)); // Hello, Guest
if (message === null)handlesnullfirst. After theif,messageis definitely a string.??uses a fallback value when the value on its left isnullorundefined. Ingreet, the fallback value is"Guest".?.givesundefinedwhen the value on its left isnull:name?.lengthhas the typenumber | undefined.
How TypeScript narrows a type inside an if like this is covered fully in the next lesson, type narrowing.
Literal type: exactly one value
Size below joins three literals. The last two lines use text that isn't in Size:
type Size = "small" | "medium" | "large";
let a: Size = "small"; // allowed
let b: Size = "jumbo"; // error
let c: Size = "Large"; // error
"small" in the type Size line isn't a value but a type: a type that may only hold the text "small". Three literals joined with | make Size, and only those three texts may go in.
| Value | In Size? |
What TypeScript says |
|---|---|---|
"small" |
yes | passes |
"jumbo" |
no | Type '"jumbo"' is not assignable to type 'Size'. (ts(2322)) |
"Large" |
no, its L is a capital | Type '"Large"' is not assignable to type 'Size'. Did you mean '"large"'? (ts(2820)) |
42 |
no | Type '42' is not assignable to type 'Size'. |
Literals can be numbers too: type Dice = 1 | 2 | 3 | 4 | 5 | 6; rejects 7 with Type '7' is not assignable to type 'Dice'. Literal types have one more benefit: the editor offers the three Size choices when you type a quote mark, so a typo is caught before the code runs.
let and const give different types
The two variables below both hold "small", but one is made with let and the other with const:
let choice = "small"; // type of choice: string
const fixed = "small"; // type of fixed: "small"
let u1: Size = choice; // error
let u2: Size = fixed; // allowed
u1 is rejected: Type 'string' is not assignable to type 'Size'. A let variable may get a new value later, for example choice = "jumbo". So TypeScript gives it the wider type, string. A type that becomes wider like this is said to widen. A const variable can't get a new value, so its type stays the literal "small". For u1 to be accepted, use const, or write the type yourself: let choice: Size = "small";.
⚠️ Capital letters, a missing hyphen, and a let that widens
- Upper and lower case differ.
"Large"is not"large". TypeScript rejects it, then suggests the right text. - Using a method only one union member has.
id.toUpperCase()is rejected forstring | number. Check withtypeoffirst. - A value from
letis rejected by a literal union.letwidens its type tostring. Useconst, or write the type. - A prefix that's slightly off.
"ID" + idgives"ID42", while the exercise asks for"ID-42", hyphen included.
TL;DR: A union A | B means the value may be A or B, for example string | number. With a union value you may only do what works on every member (every type inside the union). So check with typeof before you use a method that only strings have. A literal type is a type that holds exactly one value. type Size = "small" | "medium" | "large"; joins three literals, and only accepts those three texts. Anything else is rejected with Type '"jumbo"' is not assignable to type 'Size'. The type of a let variable holding "small" widens to string, while the type of a const variable stays the literal "small".
⚡ Union: one of several types
Write:
let code: string | number = "abc";
code = 42; // allowed
code = true; // error
Meaning: string | number is a union, read as a string or a number: the value may be either of those two types. A boolean isn't part of this union, so true is rejected.
⚡ Check with typeof first
Write:
function formatId(id: string | number): string {
if (typeof id === "string") {
return id;
}
return "ID-" + id;
}
Meaning: On a union value, you can only do what works for every member, which means every type inside the union. Without the if, id.toUpperCase() is rejected, because a number has no such method. Inside an if that checks typeof, TypeScript knows id is definitely a string.
In the exercise, formatId(42) has to give "ID-42", hyphen included.
⚡ Literal type: exactly one value
Write:
type Size = "small" | "medium" | "large";
let a: Size = "small"; // allowed
let c: Size = "Large";
Guess first: Size only accepts those three texts. Is "Large", with a capital L, accepted?
Rejected. Capital and small letters count as different, and TypeScript even suggests Did you mean '"large"'?
Meaning: "small" in the type Size line isn't a value but a type that can only hold that text. A type like this is called a literal type. Three literals joined with | make a fixed list of choices.