9.1 Union Types
Before you start, set up a new project folder named day09 exactly as you set up day01 in 1.2: open the folder in VS Code, run npm init -y and npm install --save-dev typescript in its terminal, and type the same tsconfig.json. Every program today goes in that folder.
Every type you have written so far names one kind of value. A parameter declared : number takes numbers and nothing else, which is exactly what Day 2 called static typing: the checker promises that count is always a number, so count.toFixed(2) can never crash. But real data is not always that tidy. An order number might be typed as digits, 42, or as a code, "AB-9". A player’s score might be a number, or null before the first game. A ticket might be for a numbered row or for a named area. Until today, you had to pick one type and pretend the other case did not exist.
A union type says that a value is one of several types. You write it with the | character between the choices (the same key you used for || on Day 4, pressed once): string | number reads “string or number.” A value of that type is either a string or a number; the checker does not know which until you tell it, which 9.3 shows how to do.
Worked example: A function that takes a string or a number
Day 8’s functions declared one type for each parameter. Here the parameter takes two:
function describe(value: string | number): void {
console.log(`${value} is a ${typeof value}`);
}
describe(42);
describe("forty-two");
describe(3.5);42 is a number
forty-two is a string
3.5 is a numberLine 1 declares value: string | number, so the calls on lines 5 to 7 are all accepted: 42 and 3.5 are numbers, and "forty-two" is a string. Inside the function, line 2 only puts value into a template literal and asks Day 2’s typeof what it is. Both of those work for any value, so the checker is happy. At run time there is nothing new: each call passes an ordinary value, and typeof reports what it actually got.
Now vary the argument. Pass something that is in neither half of the union:
function describe(value: string | number): void {
console.log(`${value} is a ${typeof value}`);
}
describe(true);describe-wrong-arg.ts:5:10 - error TS2345: Argument of type 'boolean' is not assignable to parameter of type 'string | number'.
TS2345 is the function version of Day 1’s TS2322: the argument on line 5, column 10, has a type that does not fit the parameter. The message shows the union exactly as you wrote it, so you can see both choices and confirm that boolean is not among them. Fix or delete this file before your next check.
What can you do with a value whose type is a union? Only what works for every member. A template literal, String(value), console.log, typeof, and === all accept any value, so they are fine. But a string method is not, because the value might be a number:
function shout(value: string | number): string {
return value.toUpperCase();
}
console.log(shout("hello"));shout-union.ts:2:16 - error TS2339: Property 'toUpperCase' does not exist on type 'string | number'.
Property 'toUpperCase' does not exist on type 'number'.
Read the two lines together. The first says the checker cannot find toUpperCase on the union; the second, indented, tells you which member is the problem: number has no toUpperCase. The checker is right to refuse. If shout(7) ran, line 2 would call a method that does not exist, and Day 3’s TypeError would stop the program. The fix is to find out which member you have before calling the method, which is 9.3. For now, fix or delete shout-union.ts.
Here is what the common ground looks like in practice:
function label(value: string | number): string {
const text = String(value);
return `[${text}] ${text.length} characters`;
}
console.log(label("Lima"));
console.log(label(2024));
console.log(label(7) === label("7"));[Lima] 4 characters
[2024] 4 characters
true
Line 2 converts value to a string first with Day 2’s String(), and from then on text is a plain string, so text.length on line 3 is allowed. Line 8 compares the two results with ===: label(7) and label("7") both give "[7] 1 characters", so it shows true.
Key idea
A | B is a union type: a value that is either an A or a B. The checker only lets you do what works for every
member; anything that works for just one member is rejected with TS2339 until you narrow the type.
Watch out
Reading | as “and”. string | number does not mean a value that is somehow both; no value is. It means one or the other, and each time the program runs, the value is exactly one of them. If you catch yourself thinking “it is a string and a number,” reread the type as “a string, or else a number.”
Pause and try
Question 1 · Tracing
Predict exactly what this program shows. A let with a union type can hold a value of either member.
let code: string | number = 7;
console.log(typeof code);
code = "seven";
console.log(typeof code);
console.log(`Code: ${code}`);
console.log(String(code).length);Check your reasoning
number
string
Code: seven
5- Line 1 declares
codeasstring | numberand stores 7, so line 2’stypeofreports number. - Line 3 stores a string in the same variable. Day 2 said a variable keeps its type, and it does: the type is still
string | number, and a string fits it. Line 4 reports string. - Line 5 puts the value in a template literal, which works for either member.
- Line 6 converts to a string first, and
"seven"has 5 characters.
Reread 9.1 Union Types if any line differed.
Question 2 · Multiple choice
price is declared as price: number | string. Which line does npx tsc accept?
console.log(price.toFixed(2));console.log(price.toUpperCase());console.log(String(price).length);console.log(price.length);
Check your reasoning
C. String(price) works for any value and gives a string, so .length is asked of a string.
- A is wrong:
toFixedbelongs to numbers only, andpricemight be a string. TS2339, withProperty 'toFixed' does not exist on type 'string'as the indented reason. - B is wrong for the same reason the other way round: a number has no
toUpperCase. - D is wrong:
lengthis a property of strings, not numbers, so the checker rejects it with TS2339 too.
Reread 9.1 Union Types if you chose differently.
9.2 Literal Types
A coffee shop sells three sizes: small, medium, and large. A parameter declared size: string accepts those three, but it also accepts "Small", "meduim", "huge", and "". Every function that takes a size has to check for nonsense, and a typo in one call is found only when a customer gets the wrong price. What you want is a type with exactly three values in it.
In 4.3 you saw that a constant has its exact value as its type: const today = "Saturday" has the type "Saturday", and the checker used it to reject today === "Sunday". A type that is one exact value is called a literal type. On its own it is not much use, because a type with one value is a constant. Put several in a union, and you get a type with exactly the values you choose:
"small" | "medium" | "large"
A union of literal types is usually given a name with a type alias, as Day 7 did for object types, so that every function can use the same list:
Worked example: Three coffee sizes
type Size = "small" | "medium" | "large";
function price(size: Size): number {
if (size === "small") {
return 3;
}
if (size === "medium") {
return 4;
}
return 5;
}
const order: Size = "medium";
console.log(`A ${order} coffee costs $${price(order)}`);
console.log(price("large"));A medium coffee costs $4
5| Line | What it does |
|---|---|
| 1 | Names the type Size; its only three values are the three strings |
| 3 | price takes a Size, so only those three strings can be passed |
| 4–10 | An if chain from Day 4 picks the price; no else for nonsense is needed |
| 13 | order is annotated Size, so it can hold one of the three and nothing else |
| 15 | A literal passed straight in is checked against the list, like line 13 |
At run time a Size is an ordinary string: order holds "medium", and price(order) compares it with "small" and "medium" using === exactly as on Day 4. The alias costs nothing when the program runs; it only tells the checker which strings are allowed.
Now vary it with a typo, and with a size the shop does not sell:
type Size = "small" | "medium" | "large";
function price(size: Size): number {
if (size === "small") {
return 3;
}
if (size === "medium") {
return 4;
}
return 5;
}
const order: Size = "meduim";
console.log(price(order));
console.log(price("huge"));coffee-typo.ts:13:7 - error TS2820: Type '"meduim"' is not assignable to type 'Size'. Did you mean '"medium"'?
coffee-typo.ts:15:19 - error TS2345: Argument of type '"huge"' is not assignable to parameter of type 'Size'.
Line 13 is caught before the program runs, and the checker even suggests the spelling you meant, because "meduim" is close to one of the three allowed values. Line 15’s "huge" is not close to anything, so it gets the plain TS2345 from 9.1. With size: string, both lines would have been accepted, and price("huge") would have quietly returned 5. Fix or delete this file.
Literal types are not only for strings. A number can be a literal type, and so can a boolean:
type DiceRoll = 1 | 2 | 3 | 4 | 5 | 6;
type Reply = "yes" | "no";
const roll: DiceRoll = 4;
const reply: Reply = "yes";
console.log(roll * 2);
console.log(reply.toUpperCase());8
YES
DiceRoll allows the six numbers 1 to 6, and roll * 2 works because every member is a number. In fact you have been using a literal union since Day 2: boolean is exactly true | false. If you meet other languages, or older TypeScript code, you may see an enum used for a fixed list of names; this course uses literal unions instead, which are plain strings with no extra syntax.
Key idea
A literal type is one exact value, such as "small" or 4. A union of literal types, usually named with a type
alias, is a type with exactly the values you list; the checker rejects anything else, including typos, before the
program runs.
Watch out
A let that forgets the list. In 4.3 you saw that a let is given a wider type than a const, because it can be assigned again. That bites with literal types:
type Size = "small" | "medium" | "large";
function price(size: Size): number {
return size === "small" ? 3 : size === "medium" ? 4 : 5;
}
let choice = "small";
choice = "large";
console.log(price(choice));coffee-let.ts:9:19 - error TS2345: Argument of type 'string' is not assignable to parameter of type 'Size'.Line 7 has no annotation, so the checker infers let choice: string: any string at all, because a let might later be given one. A string is not guaranteed to be one of the three sizes, so line 9 is rejected, even though both values ever stored in choice are sizes. The checker does not trace every assignment; it goes by the declared type. Tell it the type you mean:
type Size = "small" | "medium" | "large";
function price(size: Size): number {
return size === "small" ? 3 : size === "medium" ? 4 : 5;
}
let choice: Size = "small";
choice = "large";
console.log(price(choice));5With let choice: Size, both assignments are checked against the list, and the call is accepted. (Line 4 nests one conditional operator inside another, which Day 4 warned is hard to read; it is here only to keep the file short.) Fix or delete coffee-let.ts before your next check.
Pause and try
Question 3 · Multiple choice
Given type Answer = "yes" | "no";, which line does npx tsc accept?
const reply: Answer = "Yes";let reply: Answer = "no"; reply = "yes";const reply: Answer = "yes" || "no";let reply = "yes"; const chosen: Answer = reply;
Check your reasoning
B. Both values assigned to reply are in the list, and the annotation keeps the let from widening to string.
- A is wrong: literal types are exact, and
"Yes"with a capital letter is a different string from"yes". The checker reports it is not assignable toAnswer, and may suggest"yes". - C is wrong:
"yes" || "no"is Day 4’s||on two values, not a union. A non-empty string is always truthy, so the checker rejects the line with TS2872,This kind of expression is always truthy.The|that builds a union goes between types, never between values. - D is wrong:
let reply = "yes"has the typestring, and astringcannot be assigned toAnswer(TS2322).
Reread 9.2 Literal Types if you chose differently.
9.3 Narrowing with typeof
Back to shout-union.ts from 9.1. The function has a string | number, and it needs to call toUpperCase, which only a string has. The checker refused because the value might be a number. The way through is to ask which one it is, and the checker will follow the answer.
Day 2’s typeof gives a string naming a value’s type: typeof 42 is "number" and typeof "hi" is "string". Day 4 showed that an if can run some lines only when a condition is true. Put them together: inside if (typeof value === "number") { ... }, the value must be a number, or the block would not be running. The checker understands that. Inside the block, it treats value as a number, and lets you call number methods. Making a union type smaller by checking what the value is called narrowing, and typeof is the first tool for it.
Worked example: Formatting a string or a number
function format(value: string | number): string {
if (typeof value === "number") {
return value.toFixed(2);
}
return value.toUpperCase();
}
console.log(format(3.14159));
console.log(format("total"));
console.log(format(8));3.14
TOTAL
8.00| Line | What the checker knows about value |
Why |
|---|---|---|
| 1 | string | number |
The parameter’s declared type |
| 3 | number |
Inside the if, typeof value === "number" was true |
| 5 | string |
The if returned, so the number case can never reach here |
Line 3 is accepted because value is a number there, and toFixed exists on numbers. Line 5 is the interesting one. There is no else, but the checker notices that the if block always returns, so a number can never get past it. What is left of string | number once number is removed is string, and toUpperCase is allowed. Hover over value on line 3 and on line 5 in VS Code, and you see the two narrowed types. This is Day 8’s “return early” pattern doing double duty: it keeps the code flat, and it narrows the type for everything below.
Now vary it with three members and a full if chain:
function describe(value: string | number | boolean): string {
if (typeof value === "string") {
return `text with ${value.length} characters`;
} else if (typeof value === "number") {
return `the number ${value.toFixed(1)}`;
} else {
return value ? "yes" : "no";
}
}
console.log(describe("Hopper"));
console.log(describe(42));
console.log(describe(false));text with 6 characters
the number 42.0
no
The checker removes one member at each step. On line 3, value is string. The else if on line 4 runs only when it was not a string, so it starts from number | boolean, and its block narrows to number. The final else on line 6 gets whatever is left: boolean. That is why line 7 can put value straight into a condition and know it is a boolean. The checker is doing what you would do with a process of elimination, and it does it from the types alone, before the program runs.
Here are the typeof results you can check against, from Day 2: "string", "number", "boolean", "undefined", and, for null and every object or array, "object". That last one means typeof cannot tell null from an object, or one object type from another; 9.5 and 9.7 give the tools for those.
Key idea
Narrowing is the checker following your checks: inside if (typeof value === "number"), value is a number, and
after an if that always returns, the rest of the function has what is left of the union. Each else if removes one
more member.
Watch out
Misspelling the typeof string. The checker knows the eight strings typeof can give, and compares your condition against them:
function kind(value: string | number): string {
if (typeof value === "String") {
return "text";
}
return "a number";
}
console.log(kind("total"));typeof-capital.ts:2:7 - error TS2367: This comparison appears to be unintentional because the types '"string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function"' and '"String"' have no overlap.This is Day 4’s TS2367, and the first type in the message is the full list of typeof results, written as a literal union, the kind of type 9.2 taught. "String" with a capital S is not in it, so the comparison can never be true, and the block would never run. The three results you have not met yet, "bigint", "symbol", and "function", are for kinds of value this course does not use. Fix the spelling to "string", or delete the file.
Pause and try
Question 4 · Tracing
Predict exactly what this program shows, and say what type value has on line 3 and on line 5.
function half(value: string | number): string {
if (typeof value === "string") {
return value.slice(0, value.length / 2);
}
return String(value / 2);
}
console.log(half("Hopper"));
console.log(half(9));
console.log(half("ab").length);Check your reasoning
Hop
4.5
1On line 3, value is string, because the if checked for it; on line 5, after the if returned, it is number.
half("Hopper"): line 3 slices from 0 to6 / 2, which is 3, giving Hop.half(9): thetypeofcheck is false, so line 5 divides 9 by 2 and converts 4.5 to a string.half("ab"):2 / 2is 1, soslice(0, 1)is"a", and itslengthis 1.
Reread 9.3 Narrowing with typeof if any line differed.
Question 5 · Multiple choice
value is declared string | number | boolean. After if (typeof value === "boolean") { return "flag"; }, what is the type of value on the next line?
string | number | booleanstring | numberbooleanstring
Check your reasoning
B. The if block always returns, so a boolean never reaches the next line. The checker removes boolean from the union and keeps the rest.
- A is wrong: the whole point of narrowing is that the type gets smaller after a check that returns.
- C is wrong:
booleanis the type inside theifblock, not after it. - D is wrong: only
booleanwas ruled out; nothing has yet toldstringfromnumber.
Reread 9.3 Narrowing with typeof if you chose differently.
9.4 Narrowing with Equality
typeof tells a string from a number, but it cannot tell "red" from "green": both are strings. For a literal union, the check you need is Day 4’s ===, and the checker follows it exactly as it followed typeof. After if (light === "red"), light is "red" inside the block, and once the block returns, "red" is removed from what remains.
Worked example: What is left after each check
type Light = "red" | "yellow" | "green";
function advice(light: Light): string {
if (light === "red") {
return "Stop";
}
if (light === "yellow") {
return "Slow down";
}
return `Go: the light is ${light}`;
}
console.log(advice("red"));
console.log(advice("green"));Stop
Go: the light is green| Line | Type of light here |
Why |
|---|---|---|
| 3 | "red" | "yellow" | "green" |
The parameter’s type, Light |
| 5 | "red" |
The === on line 4 was true |
| 8 | "yellow" |
Not "red" (line 4 returned), and line 7 was true |
| 10 | "green" |
The only member not yet returned for |
Line 10 is the payoff. Hover over light there and VS Code shows "green": the checker has worked out that if the value was not red and not yellow, it can only be green, so there is no need to check. In 4.3 the checker used this kind of reasoning to tell you a comparison was impossible; now you use it on purpose.
Day 4’s switch compares one value with each case using ===, so it narrows too. Each case block sees the one literal it matched:
type Light = "red" | "yellow" | "green";
function seconds(light: Light): number {
switch (light) {
case "red":
return 30;
case "yellow":
return 3;
case "green":
return 25;
}
}
const current: Light = "yellow";
console.log(`${current} lasts ${seconds(current)} seconds`);yellow lasts 3 seconds
Something is missing from this function that Day 4 would have required: there is no default, and no return after the switch. The function promises a number, and the checker checks that every path returns one. Here it accepts the function, because the three cases cover all three members of Light, so no value can fall out of the bottom. Add a fourth member to Light without a fourth case, and the checker would complain; 9.9 shows the message and how to make it as helpful as possible.
Key idea
=== narrows a literal union: inside if (light === "red") the type is "red", and after that block returns,
"red" is removed from what remains. A switch narrows each case the same way, and the checker counts whether the
cases cover every member.
Watch out
A case for a value that is not in the union. The checker compares each case with the union, exactly as it did with Day 4’s constant in light-literal.ts:
type Light = "red" | "yellow" | "green";
function seconds(light: Light): number {
switch (light) {
case "red":
return 30;
case "yelow":
return 3;
case "green":
return 25;
}
}
console.log(seconds("red"));light-typo.ts:7:10 - error TS2678: Type '"yelow"' is not comparable to type 'Light'.TS2678 names the case value and the union it cannot match. Without the literal type, "yelow" would be a legal string, the case would never run, and a yellow light would fall through to nothing. Fix the spelling, or delete the file.
Pause and try
Question 6 · Tracing
Predict exactly what this program shows, and give the type of day on line 10.
type Day = "mon" | "tue" | "wed" | "thu" | "fri" | "sat" | "sun";
function kind(day: Day): string {
if (day === "sat" || day === "sun") {
return "weekend";
}
if (day !== "fri") {
return "weekday";
}
return `almost the weekend (${day})`;
}
console.log(kind("sun"));
console.log(kind("fri"));
console.log(kind("tue"));Check your reasoning
weekend
almost the weekend (fri)
weekdayOn line 10, day is "fri". Line 4 returned for "sat" and "sun", removing both. Line 7 returned for everything that is not "fri", so the only member left is "fri"; !== narrows just as === does, the other way round.
kind("sun"): line 4’s||is true, so weekend.kind("fri"): line 4 is false, line 7’s"fri" !== "fri"is false, and line 10 runs.kind("tue"): line 4 is false, line 7 is true, so weekday.
Reread 9.4 Narrowing with Equality if any line differed.
9.5 null and undefined in Unions
Day 2’s 2.7 left a promise. Strict mode rejects let winner: number = null; with TS2322, because null is not a number, and the fix was “a type that says the variable is sometimes a number and sometimes null.” You can now write it: number | null. The same goes for string | undefined, or any type with null or undefined added.
You have been handed values like this without the name. Day 6’s scores.at(-1) gives the last element, or undefined for an empty array, so its type is number | undefined. Day 7’s optional property subtitle?: string is a string | undefined when you read it, because the property may have been left out. Day 8’s optional parameter is the same. Each of these is a union, and the checker treats it like one: before you use the value as a number or a string, you must narrow away the “nothing” member. This is why strict mode makes you check: a number | null might be null, and null.toFixed(1) would be a runtime crash, so the checker refuses until your code has ruled that out.
Worked example: A middle name that might be missing
Not everyone has a middle name. A string | null parameter says so, and === null from Day 4 narrows it:
function initials(first: string, middle: string | null, last: string): string {
if (middle === null) {
return `${first[0]}${last[0]}`;
}
return `${first[0]}${middle[0]}${last[0]}`;
}
console.log(initials("Ada", null, "Lovelace"));
console.log(initials("Grace", "Brewster", "Hopper"));AL
GBHOn line 2, middle === null is checked. Inside that block, middle is null, and the function returns without touching it. After the block, null has been removed, so on line 5 middle is a plain string and middle[0] is allowed. The call on line 8 passes null for Ada, who is recorded without a middle name, and line 9 passes a string.
Now vary it by leaving out the check:
function initials(first: string, middle: string | null, last: string): string {
return `${first[0]}${middle[0]}${last[0]}`;
}
console.log(initials("Ada", null, "Lovelace"));initials-unchecked.ts:2:24 - error TS18047: 'middle' is possibly 'null'.
TS18047 is the message you will see most often today. Column 24 is middle at the moment it is indexed, and “possibly null” means the union still contains null there, because nothing has checked. Run with node anyway, and initials("Ada", null, "Lovelace") crashes with TypeError: Cannot read properties of null (reading '0'). The checker caught, before running, exactly the crash Day 4’s short-circuit example had to avoid by hand. Fix or delete this file.
undefined works the same way, with its own code, TS18048. Here is Day 6’s at(-1):
const scores: number[] = [72, 85, 91];
const last = scores.at(-1);
console.log(`Last score: ${last.toFixed(1)}`);last-score-unchecked.ts:3:28 - error TS18048: 'last' is possibly 'undefined'.
The array has three scores, so last is 91 when the program runs. But the checker does not count elements; it knows only that at gives number | undefined, and it will not let you call toFixed on a possible undefined. Fix or delete the file, then check both cases:
const scores: number[] = [72, 85, 91];
const empty: number[] = [];
const last = scores.at(-1);
if (last === undefined) {
console.log("No scores yet");
} else {
console.log(`Last score: ${last.toFixed(1)}`);
}
const none = empty.at(-1);
if (none === undefined) {
console.log("No scores yet");
} else {
console.log(`Last score: ${none.toFixed(1)}`);
}Last score: 91.0
No scores yet
Lines 5 and 12 compare with === undefined. In the else blocks, last and none are number, so toFixed is accepted. The empty array on line 11 really does give undefined, and the program says so instead of crashing.
There is a shorter check. Day 4 taught that null and undefined are falsy, and that if (nickname) reads “if there is a nickname.” The checker follows a truthiness check too: inside if (value), value cannot be null or undefined, so they are removed from the union. This is truthiness narrowing:
function greeting(nickname: string | undefined): string {
if (nickname) {
return `Hi, ${nickname.toUpperCase()}!`;
}
return "Hi, guest!";
}
console.log(greeting("Kim"));
console.log(greeting(undefined));
console.log(greeting(""));Hi, KIM!
Hi, guest!
Hi, guest!
On line 3, nickname is string, because undefined could not have passed the condition, so toUpperCase is allowed. Look at the third call, though: "" is a string, but it is falsy, so it also takes the guest path. For a nickname that is what you want; an empty nickname is as good as none. The Watch Out shows when it is not what you want.
Key idea
number | null and string | undefined are unions, and TS18047 (“possibly ‘null’”) or TS18048 (“possibly
‘undefined’”) means you have not narrowed the “nothing” member away. Check with === null, === undefined, or, when
0 and "" should count as nothing too, a truthiness check.
Watch out
Truthiness narrowing throws out zero. Day 4’s || could not tell “nothing” from 0, and if (count) has the same blind spot:
function report(count: number | undefined): string {
if (count) {
return `${count} items`;
}
return "Count unknown";
}
console.log(report(3));
console.log(report(undefined));
console.log(report(0));3 items
Count unknown
Count unknownNeither npx tsc nor node reports anything, and the type narrowing is correct: inside the if, count really is a number. But a real count of 0 is falsy, so the third call reports it as unknown. When 0 or "" is a real value, name the “nothing” you mean:
function report(count: number | undefined): string {
if (count !== undefined) {
return `${count} items`;
}
return "Count unknown";
}
console.log(report(3));
console.log(report(undefined));
console.log(report(0));3 items
Count unknown
0 itemscount !== undefined removes only undefined from the union, and leaves 0 as the number it is.
Pause and try
Question 7 · Tracing
Predict exactly what this program shows, and give the type of score on line 5.
function describe(score: number | null): string {
if (score === null) {
return "not graded";
}
if (!score) {
return "zero";
}
return `${score} points`;
}
console.log(describe(88));
console.log(describe(null));
console.log(describe(0));Check your reasoning
88 points
not graded
zeroOn line 5, score is number: line 2 returned for null, so only number is left. The !score on line 5 is then a plain truthiness test on a number, true only for 0 (and NaN).
describe(88): notnull, and 88 is truthy, so line 8 runs.describe(null): line 2 is true, so not graded.describe(0): notnull, but!0istrue, so zero.
Reread 9.5 null and undefined in Unions if any line differed.
Question 8 · Multiple choice
title is declared string | null. Which condition narrows title to string inside its block and treats an empty title "" as a title?
if (title)if (typeof title === "null")if (title !== null)if (title.length > 0)
Check your reasoning
C. !== null removes exactly null, so "", a string, passes into the block as a string.
- A is wrong: it narrows to
string, but""is falsy, so an empty title is treated as no title. - B is wrong:
typeof nullis"object", never"null", and the checker rejects the comparison with TS2367 because"null"is not one of thetypeofresults. - D is wrong:
title.lengthreads a property before anything has ruled outnull, so the checker reports TS18047 on the condition itself.
Reread 9.5 null and undefined in Unions if you chose differently.
9.6 Optional Chaining and Nullish Coalescing
A user record has an address, and the address has a city. But Day 7’s optional properties mean the address may be missing altogether. To show the city, you have to check the address first, every time, and a record three levels deep needs three checks. JavaScript has two operators that make this short, and the checker understands both.
Optional chaining, written ?., reads a property only if the value before it is not null or undefined. If it is one of those, the whole expression gives undefined instead of crashing. user.address?.city reads as “the address’s city, if there is an address.”
Worked example: A city that may not be there
type Address = { city: string; postcode: string };
type User = { name: string; address?: Address };
const ana: User = { name: "Ana", address: { city: "Lima", postcode: "15001" } };
const ben: User = { name: "Ben" };
console.log(ana.address?.city);
console.log(ben.address?.city);
console.log(ana.address?.city.toUpperCase());
console.log(ben.address?.city.toUpperCase());Lima
undefined
LIMA
undefined| Line | Expression | What happens |
|---|---|---|
| 7 | ana.address?.city |
address exists, so .city is read: "Lima" |
| 8 | ben.address?.city |
address is undefined, so the result is undefined |
| 9 | ana.address?.city.toUpperCase() |
The chain continues: .city is read, then toUpperCase |
| 10 | ben.address?.city.toUpperCase() |
?. found nothing, so the rest of the chain is skipped |
Line 10 is the one to understand. Once ?. meets undefined, nothing after it in the same chain runs, not even .toUpperCase(), so there is no crash. That is why a ?. is needed only at the place where something may be missing; .city and .toUpperCase() after it can use ordinary dots. The type of ben.address?.city is string | undefined: the checker adds undefined to the result to say that the chain may have stopped early.
Compare what happens without the ?.:
type Address = { city: string; postcode: string };
type User = { name: string; address?: Address };
const ben: User = { name: "Ben" };
console.log(ben.address.city);user-city-unchecked.ts:5:13 - error TS18048: 'ben.address' is possibly 'undefined'.
This is 9.5’s message pointing at the optional property. An if (ben.address !== undefined) around the line would fix it too, but ?. says the same thing in two characters. Fix or delete the file.
Optional chaining gives undefined for a missing value. Usually you want to show something instead, such as "unknown". Day 4’s || gives a default, but it also replaces 0 and "". The operator that replaces only null and undefined is nullish coalescing, written ??: a ?? b gives a unless a is null or undefined, in which case it gives b. The word nullish means “null or undefined,” the two values that mean nothing is there.
type Address = { city: string; postcode: string };
type User = { name: string; address?: Address };
const ben: User = { name: "Ben" };
const city = ben.address?.city ?? "unknown";
console.log(`${ben.name} lives in ${city}`);
const savedVolume: number | null = 0;
console.log(savedVolume ?? 50);
console.log(savedVolume || 50);
const nickname: string | undefined = "";
console.log(`[${nickname ?? "guest"}]`);
console.log(`[${nickname || "guest"}]`);Ben lives in unknown
0
50
[]
[guest]
| Line | Expression | Left side is | Result |
|---|---|---|---|
| 5 | ben.address?.city ?? "unknown" |
undefined |
"unknown" |
| 9 | savedVolume ?? 50 |
0, not nullish |
0 |
| 10 | savedVolume || 50 |
0, falsy |
50 |
| 13 | nickname ?? "guest" |
"", not nullish |
"" |
| 14 | nickname || "guest" |
"", falsy |
"guest" |
Lines 9 and 10 are Day 4’s muted music app, which || turned up to 50; ?? keeps the saved 0, because 0 is a real number, not nothing. Lines 13 and 14 show that the choice is yours: for a nickname, || is probably right, because an empty nickname should count as none, while for a volume, ?? is right. Ask “should 0 or an empty string count as missing?” and pick the operator that answers it. The checker also narrows the result: ben.address?.city ?? "unknown" has the type string, because whichever side is chosen is a string.
Key idea
a?.b reads b only when a is not nullish, and gives undefined otherwise, skipping the rest of the chain. a ?? b gives b only when a is null or undefined; unlike ||, it keeps 0 and "".
Watch out
Mixing || and ?? without parentheses. The two operators look alike but treat 0 and "" differently, so JavaScript refuses to guess which goes first:
const saved: number | null = null;
const typed: string = "";
const volume = typed || saved ?? 50;
console.log(volume);mixed-nullish.ts:3:16 - error TS5076: '||' and '??' operations cannot be mixed without parentheses.This one is not a type error but a rule of the language itself, reported by the checker and by node alike. Write (typed || saved) ?? 50 or typed || (saved ?? 50), whichever you mean, or delete the file. In most programs you want only one of the two, and the question in the table above tells you which.
Pause and try
Question 9 · Tracing
Predict exactly what this program shows.
type Owner = { name: string; phone?: string };
type Pet = { name: string; owner?: Owner };
const rex: Pet = { name: "Rex", owner: { name: "Mia" } };
const stray: Pet = { name: "Stray" };
console.log(rex.owner?.name ?? "no owner");
console.log(rex.owner?.phone ?? "no phone");
console.log(stray.owner?.phone ?? "no phone");
console.log(stray.owner?.name?.length);Check your reasoning
Mia
no phone
no phone
undefined- Line 7:
rex.ownerexists, so.nameis"Mia", which is not nullish, and??keeps it. - Line 8:
rex.ownerexists, butphonewas left out, so.phoneisundefined, and??gives no phone. - Line 9:
stray.ownerisundefined, so?.stops the chain withundefined, and??gives no phone. - Line 10: the chain stops at
?.namewithundefined; the?.lengthafter it is skipped. Nothing replaces theundefined, so it is shown as undefined.
Reread 9.6 Optional Chaining and Nullish Coalescing if any line differed.
Question 10 · Multiple choice
pages is declared number | undefined and holds 0. Which expression gives 0?
pages || 100pages ?? 100pages ? pages : 100Boolean(pages) && pages
Check your reasoning
B. ?? replaces only null and undefined, and 0 is neither, so the left side is kept.
- A is wrong: 0 is falsy, so
||gives its right side, 100. - C is wrong: the conditional operator tests truthiness, exactly like
||here, so it also gives 100. - D is wrong:
Boolean(0)isfalse, so&&gives its left side,false, not 0.
Reread 9.6 Optional Chaining and Nullish Coalescing if you chose differently.
9.7 Unions of Objects and the in Operator
Unions are not only for primitives. A pet shelter keeps cats and dogs, and they have different records: a cat’s record says whether it stays indoors, and a dog’s says how many walks it needs. Day 7’s type aliases describe each one, and a union, Cat | Dog, describes a pet that is one or the other. The rule from 9.1 still holds: you may only use what every member has.
type Cat = { name: string; indoor: boolean };
type Dog = { name: string; walksPerDay: number };
function describe(pet: Cat | Dog): string {
console.log(typeof pet);
return `${pet.name} needs ${pet.walksPerDay} walks a day`;
}
console.log(describe({ name: "Rex", walksPerDay: 2 }));pets-unchecked.ts:6:35 - error TS2339: Property 'walksPerDay' does not exist on type 'Cat | Dog'.
Property 'walksPerDay' does not exist on type 'Cat'.
pet.name on line 6 is fine, because both Cat and Dog have a name. pet.walksPerDay is not, because a Cat has none; the indented line says so. And typeof cannot help this time: line 5 would show object for a cat and for a dog alike, so the checker cannot narrow on it. Fix or delete the file.
What tells a dog’s record from a cat’s is which properties it has. JavaScript’s in operator asks exactly that: "walksPerDay" in pet is true when pet has a property named walksPerDay. The property name goes on the left, as a string in quotes, and the object on the right. The checker follows in as a narrowing check: inside if ("walksPerDay" in pet), pet is narrowed to the members that have that property.
Worked example: Describing a cat or a dog
type Cat = { name: string; indoor: boolean };
type Dog = { name: string; walksPerDay: number };
function describe(pet: Cat | Dog): string {
if ("walksPerDay" in pet) {
return `${pet.name} needs ${pet.walksPerDay} walks a day`;
}
return `${pet.name} ${pet.indoor ? "stays inside" : "goes out"}`;
}
const rex: Dog = { name: "Rex", walksPerDay: 2 };
const tom: Cat = { name: "Tom", indoor: true };
console.log(describe(rex));
console.log(describe(tom));Rex needs 2 walks a day
Tom stays inside| Line | Type of pet here |
Why |
|---|---|---|
| 4 | Cat | Dog |
The parameter’s declared type |
| 6 | Dog |
Only a Dog has walksPerDay |
| 8 | Cat |
The if returned, so what is left cannot be a Dog |
Line 6 may read pet.walksPerDay, and line 8 may read pet.indoor, each because the checker has narrowed to the one type that has the property. At run time, in simply looks for the property name in the object: Rex has one called walksPerDay, and Tom does not.
in checks for the property’s presence, not its value: an object with walksPerDay: 0 still has the property, so in gives true. That is a difference from a truthiness check on the value.
Key idea
A union of object types allows only the properties every member has. "name" in object is true when the object has
that property, and inside the if the checker narrows the union to the members that have it.
Watch out
Forgetting the quotes. The left side of in is a string. Without quotes, the checker looks for a variable with that name:
type Cat = { name: string; indoor: boolean };
type Dog = { name: string; walksPerDay: number };
function describe(pet: Cat | Dog): string {
if (walksPerDay in pet) {
return `${pet.name} needs walks`;
}
return `${pet.name} is a cat`;
}
console.log(describe({ name: "Tom", indoor: true }));in-no-quotes.ts:5:7 - error TS2304: Cannot find name 'walksPerDay'.Day 1’s TS2304: there is no variable called walksPerDay, only a property. Write "walksPerDay" in pet, or delete the file.
Pause and try
Question 11 · Tracing
Predict exactly what this program shows.
type Email = { address: string; subject: string };
type Text = { number: string; body: string };
function summary(message: Email | Text): string {
if ("subject" in message) {
return `Email to ${message.address}: ${message.subject}`;
}
return `Text to ${message.number} (${message.body.length} characters)`;
}
console.log(summary({ number: "555-0100", body: "Running late" }));
console.log(summary({ address: "ana@example.com", subject: "Hello" }));Check your reasoning
Text to 555-0100 (12 characters)
Email to ana@example.com: Hello- Line 11 passes an object with
numberandbody. Line 5 asks whether it has asubject; it does not, so line 8 runs withmessagenarrowed toText."Running late"has 12 characters. - Line 12’s object has a
subject, so line 6 runs withmessagenarrowed toEmail.
Reread 9.7 Unions of Objects and the in Operator if either line differed.
9.8 Discriminated Unions
in works, but it leans on the members having different property names. Imagine a Square with a side and a Rectangle with width and height; now add a Rhombus, which also has a side. "side" in shape can no longer tell them apart, and the checker’s narrowing gets vaguer as the shapes grow. A sturdier design is to give every member a property that says what it is.
A discriminated union is a union of object types that each have the same property, called the discriminant (or the tag), holding a different literal type in each member: kind: "circle" in one, kind: "square" in the other. Reading shape.kind is always allowed, because every member has it, and comparing it with === narrows to the one member with that literal.
Worked example: Shapes that announce themselves
type Circle = { kind: "circle"; radius: number };
type Square = { kind: "square"; side: number };
type Shape = Circle | Square;
function describe(shape: Shape): string {
if (shape.kind === "circle") {
return `a circle of radius ${shape.radius}`;
}
return `a square with side ${shape.side}`;
}
const shapes: Shape[] = [
{ kind: "circle", radius: 2 },
{ kind: "square", side: 3 },
];
for (const shape of shapes) {
console.log(describe(shape));
}a circle of radius 2
a square with side 3| Line | What happens |
|---|---|
| 1–2 | Each type has a kind with its own literal type, plus its own measurements |
| 3 | Shape is the union; kind is the discriminant |
| 6 | shape.kind === "circle" narrows shape to Circle, so line 7 may read radius |
| 9 | The if returned, so shape is Square here and side is allowed |
| 12 | An array of Shape can hold both kinds; each literal’s kind picks its member |
At run time, kind is an ordinary string property, and === compares it, as in every program since Day 4. The design is the new part: each object carries its own label, so the function never has to guess from which properties happen to be present.
Because the discriminant is a literal union, 9.4’s switch fits it perfectly:
type Circle = { kind: "circle"; radius: number };
type Square = { kind: "square"; side: number };
type Shape = Circle | Square;
function perimeter(shape: Shape): number {
switch (shape.kind) {
case "circle":
return 2 * Math.PI * shape.radius;
case "square":
return 4 * shape.side;
}
}
console.log(perimeter({ kind: "square", side: 3 }));
console.log(perimeter({ kind: "circle", radius: 1 }).toFixed(2));12
6.28
Inside case "circle":, shape is Circle, and inside case "square": it is Square. As in light-switch.ts, there is no default: the two cases cover both members, so the checker accepts a function that returns only inside them. Math.PI is the number π, 3.14159…, which is why line 15 rounds with toFixed.
Key idea
A discriminated union gives every member the same property with a different literal type, such as kind: "circle" and
kind: "square". Comparing that property with ===, in an if or a switch, narrows to exactly one member.
Watch out
Declaring the discriminant as string. The narrowing only works when each member’s kind is a literal type:
type Circle = { kind: string; radius: number };
type Square = { kind: string; side: number };
type Shape = Circle | Square;
function describe(shape: Shape): string {
if (shape.kind === "circle") {
return `a circle of radius ${shape.radius}`;
}
return `a square with side ${shape.side}`;
}
console.log(describe({ kind: "circle", radius: 2 }));shapes-string-kind.ts:7:40 - error TS2339: Property 'radius' does not exist on type 'Shape'.
Property 'radius' does not exist on type 'Square'.
shapes-string-kind.ts:9:38 - error TS2339: Property 'side' does not exist on type 'Shape'.
Property 'side' does not exist on type 'Circle'.With kind: string in both members, shape.kind === "circle" tells the checker nothing about which member it has, because either one could hold the string "circle". So shape stays Shape on lines 7 and 9, and 9.7’s TS2339 appears for each property that only one member has. Write kind: "circle" and kind: "square", with the quotes, in the type aliases, or delete the file.
Pause and try
Question 12 · Tracing
Predict exactly what this program shows, and give the type of page on line 13.
type Loading = { state: "loading" };
type Done = { state: "done"; items: string[] };
type Failed = { state: "failed"; reason: string };
type Page = Loading | Done | Failed;
function message(page: Page): string {
if (page.state === "loading") {
return "Please wait...";
}
if (page.state === "failed") {
return `Could not load: ${page.reason}`;
}
return `${page.items.length} items loaded`;
}
console.log(message({ state: "done", items: ["pen", "ink"] }));
console.log(message({ state: "failed", reason: "no connection" }));
console.log(message({ state: "loading" }));Check your reasoning
2 items loaded
Could not load: no connection
Please wait...On line 13, page is Done: line 7 returned for "loading" and line 10 for "failed", so the only member left is the one whose state is "done", and that is why page.items is allowed there.
- The first call has
state: "done", so bothifs are false and line 13 counts two items. - The second has
state: "failed", narrowing toFailedon line 11, wherereasonis allowed. - The third matches line 7.
Reread 9.8 Discriminated Unions if any line differed.
Question 13 · Multiple choice
Which type can be narrowed with if (event.type === "click") so that event.x is allowed inside the block?
type Event = { type: string; x: number } | { type: string; key: string }type Event = { type: "click"; x: number } | { type: "key"; key: string }type Event = { x: number } | { key: string }type Event = { type: "click" | "key"; x: number; key: string }
Check your reasoning
B. Each member has type with its own literal, so === "click" narrows to the first member, which has x.
- A is wrong: with
type: stringin both members, the comparison tells the checker nothing, andxis rejected with TS2339. - C is wrong: neither member has a
typeproperty, soevent.typeis rejected before the comparison is even made. This union could be narrowed with"x" in event, but not with===. - D is wrong: it is not a union of objects at all but one object type with both
xandkeyalways present.event.xis allowed everywhere, with no narrowing needed, and a key event would have to carry a meaninglessx.
Reread 9.8 Discriminated Unions if you chose differently.
9.9 Exhaustive switch with never
perimeter.ts handles circles and squares. Programs grow: next month someone adds a Triangle to Shape. Every switch over shape.kind in the program now has a missing case, and the bug is silent unless something makes the checker notice. 9.4 promised it would. Here is what it says when the triangle is added but the switch is not updated:
type Circle = { kind: "circle"; radius: number };
type Square = { kind: "square"; side: number };
type Triangle = { kind: "triangle"; a: number; b: number; c: number };
type Shape = Circle | Square | Triangle;
function perimeter(shape: Shape): number {
switch (shape.kind) {
case "circle":
return 2 * Math.PI * shape.radius;
case "square":
return 4 * shape.side;
}
}
console.log(perimeter({ kind: "square", side: 3 }));perimeter-missing.ts:6:35 - error TS2366: Function lacks ending return statement and return type does not include 'undefined'.
The checker has counted: two cases, three members, so a triangle falls out of the bottom of the switch and reaches the end of the function without returning a number. That is caught, which is good. But look where the message points: line 6, column 35, the function’s return type, and it says nothing about triangles. In a long function with many cases, you would have to work out for yourself which member is missing. Fix or delete this file; there is a better way to write the same check.
A switch that handles every member of a union is called exhaustive. To make the checker say exactly which member is not handled, add a default and assign the value to a variable of type never. never is the type with no values at all. The checker gives a value this type when it has narrowed away every member of a union: in the default of an exhaustive switch, shape has been shown not to be a circle and not to be a square, and if those were the only members, nothing is left, so shape is never. Assigning a never to a never is fine. But if a member was not handled, shape in the default still has that member’s type, and that type cannot be assigned to never:
type Circle = { kind: "circle"; radius: number };
type Square = { kind: "square"; side: number };
type Triangle = { kind: "triangle"; a: number; b: number; c: number };
type Shape = Circle | Square | Triangle;
function perimeter(shape: Shape): number {
switch (shape.kind) {
case "circle":
return 2 * Math.PI * shape.radius;
case "square":
return 4 * shape.side;
default: {
const unhandled: never = shape;
return unhandled;
}
}
}
console.log(perimeter({ kind: "square", side: 3 }));perimeter-never.ts:13:13 - error TS2322: Type 'Triangle' is not assignable to type 'never'.
Now the message names the missing member, Triangle, and points at the never check on line 13, which is where you go to add the case. Read const unhandled: never = shape; as “I claim nothing can reach here,” and the checker tells you whether the claim is true. Line 14 returns unhandled so that the default block gives the function a value on every path; because its type is never, it fits any return type, and when every case is handled, the line can never run. Fix or delete this file, then write the complete version:
type Circle = { kind: "circle"; radius: number };
type Square = { kind: "square"; side: number };
type Triangle = { kind: "triangle"; a: number; b: number; c: number };
type Shape = Circle | Square | Triangle;
function perimeter(shape: Shape): number {
switch (shape.kind) {
case "circle":
return 2 * Math.PI * shape.radius;
case "square":
return 4 * shape.side;
case "triangle":
return shape.a + shape.b + shape.c;
default: {
const unhandled: never = shape;
return unhandled;
}
}
}
console.log(perimeter({ kind: "triangle", a: 3, b: 4, c: 5 }));
console.log(perimeter({ kind: "square", side: 2.5 }));12
10
With the "triangle" case added, shape in the default is never, the assignment is accepted, and npx tsc is quiet. Nothing changed at run time: a triangle matches its case and returns before the default is ever reached. The never check costs one line and turns “a future bug” into “a message that names what you forgot.”
The braces around the default block, default: { ... }, are there because the block declares a constant. Without them, a const declared in one case would share its scope with every other case of the switch; the braces give it its own block, as Day 4’s if blocks have.
Key idea
A switch over a discriminant is exhaustive when it handles every member. End it with default: { const unhandled: never = shape; return unhandled; }; when every member is handled, shape is never there and the checker is quiet,
and when one is missing, TS2322 names it.
Watch out
Writing default: return 0; instead. A default that returns a made-up value also satisfies “every path returns a number,” so the checker accepts it, and a triangle quietly gets a perimeter of 0. The never check is the version that complains when a member is missing, which is the whole point. Use default for a real fallback only when a value really can fall outside the list, and that is never the case for a union the checker already knows in full.
Pause and try
Question 14 · Multiple choice
Status is "draft" | "sent" | "paid". A switch (status) has cases for "draft" and "sent" and ends with default: { const unhandled: never = status; return unhandled; }. What does npx tsc report?
- Nothing: the
defaulthandles"paid" - TS2322,
Type '"paid"' is not assignable to type 'never' - TS2366,
Function lacks ending return statement - TS2678,
Type '"paid"' is not comparable to type 'Status'
Check your reasoning
B. In the default, status has had "draft" and "sent" removed, leaving "paid", and "paid" is not never. The message names exactly the member that was forgotten.
- A is wrong: the
defaultdoes run for"paid"at run time, but thenevercheck exists precisely so that the checker refuses the program until acase "paid":is written. - C is wrong: TS2366 is the message without a
default, when a path can fall out of theswitch. Here every path returns. - D is wrong: TS2678 is for a
casevalue that is not in the union;"paid"is in it, and there is no case for it at all.
Reread 9.9 Exhaustive switch with never if you chose differently.
Putting it together
A parcel is either ordered, shipped, or delivered. Every parcel has an order id that may be a number or a text code. A shipped parcel has a carrier and maybe an expected day; a delivered one records who signed, or null when nobody did. Before you type it, make sure npx tsc is clean in your day09 folder: fix or delete any broken file from today.
type Ordered = { kind: "ordered"; orderId: string | number };
type Shipped = { kind: "shipped"; orderId: string | number; carrier: string; eta?: string };
type Delivered = { kind: "delivered"; orderId: string | number; signedBy: string | null };
type Parcel = Ordered | Shipped | Delivered;
function orderLabel(orderId: string | number): string {
if (typeof orderId === "number") {
return String(orderId).padStart(5, "0");
}
return orderId.toUpperCase();
}
function status(parcel: Parcel): string {
const label = orderLabel(parcel.orderId);
switch (parcel.kind) {
case "ordered":
return `${label}: order received`;
case "shipped":
return `${label}: with ${parcel.carrier}, arriving ${parcel.eta ?? "soon"}`;
case "delivered":
return `${label}: delivered, signed by ${parcel.signedBy ?? "nobody"}`;
default: {
const unhandled: never = parcel;
return unhandled;
}
}
}
const parcels: Parcel[] = [
{ kind: "ordered", orderId: 42 },
{ kind: "shipped", orderId: "ab-9", carrier: "PostFast" },
{ kind: "shipped", orderId: 7, carrier: "Swift", eta: "Tuesday" },
{ kind: "delivered", orderId: "zz-1", signedBy: null },
];
for (const parcel of parcels) {
console.log(status(parcel));
}npx tsc reports no errors, and node parcel.ts shows:
00042: order received
AB-9: with PostFast, arriving soon
00007: with Swift, arriving Tuesday
ZZ-1: delivered, signed by nobody
Follow the fourth parcel, { kind: "delivered", orderId: "zz-1", signedBy: null }, through the program:
| Line | What happens | Idea |
|---|---|---|
| 1–4 | Three members share kind and orderId; Parcel is their union |
9.8 |
| 14 | parcel.orderId is allowed: every member has it |
9.1 |
| 7 | typeof says "zz-1" is not a number, so line 10 runs |
9.3 |
| 10 | orderId is string here, so toUpperCase gives "ZZ-1" |
9.3 |
| 15 | switch on the discriminant |
9.8 |
| 20 | case "delivered" matches, so parcel is Delivered and has signedBy |
9.8 |
| 21 | signedBy is null, so ?? gives "nobody" |
9.6 |
| 22–25 | Never reached, and the never check proves nothing was forgotten |
9.9 |
For the first parcel, line 8 pads "42" with Day 3’s padStart to five characters. The second parcel has no eta, so parcel.eta on line 19 is undefined and ?? supplies "soon"; the third has one, and ?? keeps it. Each operator does one job: typeof tells the two kinds of id apart, the switch on kind tells the three kinds of parcel apart, ?? fills the gaps, and never guards against a fourth kind being added later without a case.
Common mistakes
Today’s messages in one place. All come from npx tsc, except the last two rows, which show no message at all.
| Message or symptom | Usual cause | Fix |
|---|---|---|
TS2339: Property 'toUpperCase' does not exist on type 'string | number'. |
Using a member’s method before narrowing | Narrow with typeof, ===, or in first |
TS2345: Argument of type 'string' is not assignable to parameter of type 'Size'. |
A let without an annotation widened to string |
let choice: Size = ... |
TS2820: Type '"meduim"' is not assignable to type 'Size'. Did you mean '"medium"'? |
A typo in a literal | Use the suggested spelling |
TS2367: ... '"string" | "number" | ...' and '"String"' have no overlap. |
A misspelled typeof result |
Lowercase: "string", "number" |
TS2678: Type '"yelow"' is not comparable to type 'Light'. |
A case value not in the union |
Fix the spelling |
TS18047: 'middle' is possibly 'null'. / TS18048: ... 'undefined'. |
Using a value before ruling out the “nothing” member | === null, !== undefined, ?., or ?? |
TS5076: '||' and '??' operations cannot be mixed without parentheses. |
a || b ?? c |
Add parentheses, or use just one operator |
TS2304: Cannot find name 'walksPerDay'. on an in check |
Missing quotes around the property name | "walksPerDay" in pet |
TS2366: Function lacks ending return statement ... |
A switch with a member missing and no default |
Add the case, and a never check |
TS2322: Type 'Triangle' is not assignable to type 'never'. |
The never check found an unhandled member |
Add case "triangle": |
if (count) skips a real 0 |
Truthiness narrowing treats 0 and "" as nothing |
count !== undefined, or ?? for defaults |
shape.kind === "circle" does not narrow |
The discriminant was declared string |
Give each member a literal: kind: "circle" |
Vocabulary
| Term | Definition | Example |
|---|---|---|
| union type | A type whose value is one of several types, written with | |
string | number |
| literal type | A type with exactly one value | "small", 4 |
| narrowing | The checker making a union smaller by following a check in your code | if (typeof value === "number") |
| truthiness narrowing | Narrowing by putting the value itself in a condition; removes null, undefined, and also 0 and "" |
if (nickname) |
| optional chaining | ?.: read a property only if the value before it is not nullish, else undefined |
user.address?.city |
| nullish | null or undefined: the two values that mean nothing is there |
undefined ?? "x" gives "x" |
| nullish coalescing | ??: give the right side only when the left is nullish |
savedVolume ?? 50 |
in operator |
"name" in object is true when the object has that property |
"walksPerDay" in pet |
| discriminated union | A union of object types that share a property with a different literal in each | Circle | Square |
| discriminant | That shared property, also called the tag | kind |
| exhaustive | A switch that handles every member of a union |
Cases for "circle", "square", "triangle" |
never |
The type with no values; what is left of a union when every member is ruled out | const unhandled: never = shape; |
Summary
- A union type
A | Bis a value that is one of several types, and a literal type is one exact value; a union of literals such as"small" | "medium" | "large"is a type with exactly the values you list, and the checker rejects everything else, typos included. - With a union you may only do what works for every member; to do more, narrow it. The checker follows
typeoffor primitives,===andswitchfor literals,=== nulland truthiness fornullandundefined, andinfor objects, and it removes each member a returningifhas handled. number | nullandstring | undefinedare how strict mode lets a value be missing; TS18047 and TS18048 mean you have not ruled the “nothing” member out yet. Truthiness narrowing is short but also throws out0and"".a?.breadsbonly whenais not nullish and skips the rest of the chain otherwise;a ?? bgives a default only fornullandundefined, where||would also replace0and"".- A discriminated union gives each member a
kindwith its own literal, so one===orswitchnarrows to exactly one member; adefaultthat assigns tonevermakes the checker name any member theswitchforgot.
Practice
Do these in your day09 folder. First make sure npx tsc prints nothing there: if any broken file from today is still in the folder (such as describe-wrong-arg.ts, shout-union.ts, coffee-typo.ts, coffee-let.ts, typeof-capital.ts, light-typo.ts, initials-unchecked.ts, last-score-unchecked.ts, user-city-unchecked.ts, mixed-nullish.ts, pets-unchecked.ts, in-no-quotes.ts, shapes-string-kind.ts, perimeter-missing.ts, or perimeter-never.ts), fix it or delete it. Then type each program yourself, check it with npx tsc, run it with node, and only then open the answer. Change the calls at the bottom and run them again.
Question 15 · Short answer
Format an id. Write formatId(id: string | number): string. A number is padded with zeros to six digits (42 becomes "000042"); a string is returned in capitals. Call it with a small number, a number longer than six digits, and a string.
Check your reasoning
One possible solution:
/** Pads a numeric id to six digits and uppercases a text id. */
function formatId(id: string | number): string {
if (typeof id === "number") {
return String(id).padStart(6, "0");
}
return id.toUpperCase();
}
console.log(formatId(42));
console.log(formatId(123456789));
console.log(formatId("abc-7"));000042
123456789
ABC-7typeof id === "number" narrows id to number inside the if; padStart is a string method, so the number is converted with String() first, then padded to width 6 with "0". Day 3 said padStart leaves a string alone when it is already long enough, which is why the nine-digit number comes back unchanged. After the if returns, id is string, so toUpperCase is allowed on the last line. The doc comment on line 1 is Day 8’s: hover over formatId in a call and VS Code shows it.
Reread 9.3 Narrowing with typeof if your result differed.
Question 16 · Short answer
Area of a shape. Define a discriminated union of three shapes, a circle with a radius, a square with a side, and a rectangle with a width and a height, and write area(shape) as an exhaustive switch with a never check. Print the area of one of each, rounded to two places. (The area of a circle is π times the radius squared; Math.PI is π and ** is Day 2’s power operator.)
Check your reasoning
One possible solution:
type Circle = { kind: "circle"; radius: number };
type Square = { kind: "square"; side: number };
type Rectangle = { kind: "rectangle"; width: number; height: number };
type Shape = Circle | Square | Rectangle;
function area(shape: Shape): number {
switch (shape.kind) {
case "circle":
return Math.PI * shape.radius ** 2;
case "square":
return shape.side ** 2;
case "rectangle":
return shape.width * shape.height;
default: {
const unhandled: never = shape;
return unhandled;
}
}
}
const shapes: Shape[] = [
{ kind: "circle", radius: 1 },
{ kind: "square", side: 3 },
{ kind: "rectangle", width: 2, height: 4.5 },
];
for (const shape of shapes) {
console.log(`${shape.kind}: ${area(shape).toFixed(2)}`);
}circle: 3.14
square: 9.00
rectangle: 9.00Each member has kind with its own literal, so switch (shape.kind) narrows shape to one member per case: radius is allowed only inside case "circle":, and so on. The default assigns shape to a never; with all three cases written, the checker is quiet. Try it: delete the "rectangle" case and run npx tsc, and you get Type 'Rectangle' is not assignable to type 'never'. Put it back before you go on. The loop at the bottom reads shape.kind outside the function, which is allowed without narrowing because every member has it.
Reread 9.8 Discriminated Unions and 9.9 Exhaustive switch with never if your result differed.
Question 17 · Short answer
Display name. A profile has an email, and may or may not have a name and a nickname (both optional properties). Write displayName(profile) that returns the nickname if there is one, otherwise the name, otherwise "Anonymous". Test it with a profile that has both, one with only a name, and one with neither.
Check your reasoning
One possible solution:
type Profile = { name?: string; nickname?: string; email: string };
/** The nickname if there is one, otherwise the name, otherwise a stand-in. */
function displayName(profile: Profile): string {
return profile.nickname ?? profile.name ?? "Anonymous";
}
const users: Profile[] = [
{ name: "Ada Lovelace", nickname: "Ada", email: "ada@example.com" },
{ name: "Grace Hopper", email: "grace@example.com" },
{ email: "mystery@example.com" },
];
for (const user of users) {
console.log(displayName(user));
}Ada
Grace Hopper
AnonymousAn optional property reads as string | undefined, and ?? gives its right side only for undefined, so profile.nickname ?? profile.name ?? "Anonymous" works from left to right: the first value that is not nullish wins. The result is a string, because the final fallback is always a string, which is why the function can promise : string without an if in sight. If you decided that an empty nickname, "", should fall through to the name, || in place of the first ?? does that, and that choice is yours to make, as 9.6 explained.
Reread 9.6 Optional Chaining and Nullish Coalescing and 9.5 null and undefined in Unions if your result differed.
Review questions
Question 18 · Tracing
Predict exactly what this program shows. The third call is the one to think about.
type Ticket = { seat: string | number; holder?: string };
function describe(ticket: Ticket): string {
const seat = typeof ticket.seat === "number" ? `row ${ticket.seat}` : ticket.seat.toLowerCase();
const holder = ticket.holder ?? "unclaimed";
return `${seat} (${holder})`;
}
console.log(describe({ seat: 12, holder: "Ravi" }));
console.log(describe({ seat: "BALCONY" }));
console.log(describe({ seat: 0, holder: "" }));Check your reasoning
row 12 (Ravi)
balcony (unclaimed)
row 0 ()Line 4 narrows ticket.seat with typeof inside a conditional operator: in the true branch it is number, in the false branch string, so toLowerCase is allowed there. The checker follows a check on a property, ticket.seat, just as it does on a variable.
- First call: a number seat and a holder.
- Second:
"BALCONY"is lowercased, andholderwas left out, so??gives unclaimed. - Third:
0is a number, sotypeofsends it down therowbranch; and""is not nullish, so??keeps it, giving empty parentheses. With||instead, it would have shownunclaimed.
Reread 9.3 Narrowing with typeof and 9.6 Optional Chaining and Nullish Coalescing if any line differed.
Question 19 · Multiple choice
Here is a working program:
type Reading = { kind: "temperature"; celsius: number } | { kind: "humidity"; percent: number };
function show(reading: Reading): string {
if (reading.kind === "temperature") {
return `${reading.celsius} °C`;
}
return `${reading.percent}% humidity`;
}
console.log(show({ kind: "humidity", percent: 55 }));Which one change makes npx tsc reject it?
- Replacing line 4’s condition with
"celsius" in reading - Replacing line 4’s condition with
typeof reading === "temperature" - Adding a third call,
show({ kind: "temperature", celsius: -4 }) - Changing line 5 to
return `${reading.celsius.toFixed(1)} °C`;
Check your reasoning
B. typeof gives one of eight fixed strings, and "temperature" is not among them; the checker reports TS2367 because the comparison can never be true. typeof would say "object" for either reading.
- A is wrong:
innarrows the union by property, and only the temperature member hascelsius, so line 5 still type-checks. - C is wrong: the object matches the first member exactly, and negative numbers are numbers.
- D is wrong: inside the
if,readingis narrowed to the temperature member, socelsiusis anumberandtoFixedis allowed.
Reread 9.3 Narrowing with typeof and 9.7 Unions of Objects and the in Operator if you chose differently.
Question 20 · Debugging
Someone added vouchers to the shop’s payment types, and npx tsc now rejects this program. Predict the message, explain it, and write the fix.
type Card = { method: "card"; last4: string };
type Cash = { method: "cash" };
type Voucher = { method: "voucher"; code: string; remaining: number };
type Payment = Card | Cash | Voucher;
function receiptLine(payment: Payment): string {
switch (payment.method) {
case "card":
return `Card ending ${payment.last4}`;
case "cash":
return "Cash";
default: {
const unhandled: never = payment;
return unhandled;
}
}
}
console.log(receiptLine({ method: "cash" }));Check your reasoning
review-payment.ts:13:13 - error TS2322: Type 'Voucher' is not assignable to type 'never'.The switch handles "card" and "cash", so in the default, payment has had those two members removed and is Voucher, not never. The never check on line 13 refuses, and names the member that has no case. Without that line the checker would have accepted the function, because the default returns, and a voucher would have come back as undefined at run time. The fix is the case the message asks for:
type Card = { method: "card"; last4: string };
type Cash = { method: "cash" };
type Voucher = { method: "voucher"; code: string; remaining: number };
type Payment = Card | Cash | Voucher;
function receiptLine(payment: Payment): string {
switch (payment.method) {
case "card":
return `Card ending ${payment.last4}`;
case "cash":
return "Cash";
case "voucher":
return `Voucher ${payment.code} (${payment.remaining} left)`;
default: {
const unhandled: never = payment;
return unhandled;
}
}
}
console.log(receiptLine({ method: "voucher", code: "SPRING", remaining: 4 }));Voucher SPRING (4 left)Inside case "voucher":, payment is Voucher, so code and remaining are allowed. If you typed the original program, fix or delete it before you go on.
Reread 9.9 Exhaustive switch with never if you missed it.
Question 21 · Tracing
Predict exactly what this program shows.
type Settings = { theme?: "light" | "dark"; fontSize?: number; profile?: { nickname?: string } };
const mine: Settings = { fontSize: 0, profile: {} };
console.log(mine.theme ?? "light");
console.log(mine.fontSize ?? 16);
console.log(mine.fontSize || 16);
console.log(mine.profile?.nickname ?? "none");
console.log(mine.profile?.nickname?.length);Check your reasoning
light
0
16
none
undefined- Line 5:
themewas left out, so it isundefined, and??gives light. - Line 6:
fontSizeis 0, which is not nullish, so??keeps 0. - Line 7: 0 is falsy, so
||replaces it with 16. This is the only line where the two operators differ. - Line 8:
profileexists but is empty, so?.nicknameisundefined, and??gives none. - Line 9: the chain reaches
?.nickname, findsundefined, skips?.length, and nothing replaces the result: undefined.
Reread 9.6 Optional Chaining and Nullish Coalescing if any line differed.
Question 22 · Short answer
Sam has type Pet = Cat | Dog from 9.7 and writes if (typeof pet === "Dog") to tell them apart. Explain why that cannot work, and describe the two ways that do, saying when you would choose each.
Check your reasoning
Model answer: typeof reports only the eight built-in kinds of value, and for any object it gives "object", so a cat and a dog look the same to it; the checker also rejects the comparison with TS2367 because "Dog" is not one of the eight strings. To tell object types apart, either check for a property only one of them has, with "walksPerDay" in pet, or give each type a discriminant such as kind: "cat" and kind: "dog" and compare it with ===. The in check needs no change to the types and is fine for two types with clearly different properties; the discriminant is the sturdier design when there are several members, when some share property names, or when you want an exhaustive switch with a never check.
A complete answer must:
- say that
typeofgives"object"for every object, so it cannot distinguish them, - name
inon a property that only one member has, and - name a discriminant property with a literal type in each member, compared with
===or aswitch.
Reread 9.7 Unions of Objects and the in Operator and 9.8 Discriminated Unions if your reasoning differed.
Question 23 · Multiple choice
label is declared let label: "on" | "off" | undefined; and nothing has been assigned to it yet. Which line does npx tsc accept and show off when run?
console.log(label.toUpperCase());console.log(label ?? "off");console.log(label === "off" ? "off" : "on");console.log(label || "on");
Check your reasoning
B. label holds undefined, so ?? gives its right side, "off". The checker accepts it because ?? needs no narrowing: it is the check.
- A is wrong:
labelis possiblyundefined, so calling a method on it is TS18048. - C is wrong: the checker accepts it, but
labelholdsundefined, andundefined === "off"is false, so it showson. - D is wrong:
undefinedis falsy, so||gives"on", not"off".
Reread 9.6 Optional Chaining and Nullish Coalescing and 9.5 null and undefined in Unions if you chose differently.
Go further
The Handbook’s page on narrowing covers every check the checker follows, including typeof, truthiness, equality, in, and discriminated unions with never: TypeScript Handbook: Narrowing. Its “Everyday Types” page has the union and literal type sections this day started from: TypeScript Handbook: Everyday Types.
Reflection
Check each statement. If the answer is “not yet,” reread the linked subsection.
- I can write a union type and say what the checker lets me do with it before narrowing. Reread
- I can define a literal union with a type alias and explain why a let needs an annotation to use it. Reread
- I can narrow a string | number with typeof and say what type is left after an early return. Reread
- I can narrow a literal union with === or a switch. Reread
- I can read TS18047 and TS18048 and rule out null or undefined with ===, or with a truthiness check when 0 and "" should count as nothing. Reread
- I can use ?. to reach into data that may be missing and ?? to give it a default, and say how ?? differs from ||. Reread
- I can tell two object types apart with in. Reread
- I can design a discriminated union and narrow it on its kind. Reread
- I can write an exhaustive switch with a never check and explain the message it gives when a case is missing. Reread