10.1 Interfaces
Before you start, set up a new project folder named day10 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.
On Day 7 you described the shape of an object with a type alias: type Book = { title: string; pages: number } told the checker which properties a book has and what type each one holds. Today you meet a second way to say the same thing, the interface, which most TypeScript code uses for objects, and which has one ability a plain alias lacks: one interface can be built on top of another, as 10.2 shows.
An interface is a named description of an object’s shape: the properties the object must have, and the type of each. It is written with the keyword interface, a name, and a block of properties:
interface Name {
property: type;
property: type;
}
| Piece | What it is |
|---|---|
interface |
The keyword that starts the description |
Name |
The interface’s name, written in PascalCase with a capital first letter, like a type alias |
{ and } |
The block that lists the properties; there is no = before it and no semicolon after it |
property: type |
One property and the type of its value, ended with a semicolon, exactly as inside a type alias |
Like a type alias, an interface is a line for the checker only. Day 1’s two-step rule applies: npx tsc reads it to check your objects, and node strips it out before running, so an interface never creates anything and never prints anything.
Worked example: Describing an employee
The program describes what every employee record looks like, then makes two of them.
interface Employee {
name: string;
salary: number;
}
const ana: Employee = { name: "Ana Reyes", salary: 52000 };
const ben: Employee = { name: "Ben Okafor", salary: 48500 };
console.log(`${ana.name} earns $${ana.salary} a year.`);
console.log(`${ben.name} earns $${ben.salary} a year.`);
console.log(ana.salary + ben.salary);Ana Reyes earns $52000 a year.
Ben Okafor earns $48500 a year.
100500| Line | What happens |
|---|---|
| 1–4 | The checker learns that an Employee is an object with a name string and a salary number |
| 6 | The annotation : Employee makes the checker compare the object literal with the interface: both properties, correct types |
| 7 | The same check for ben |
| 9–10 | Property access with the dot, as on Day 7; the checker knows name is a string and salary is a number |
| 11 | Because both salaries are numbers, + adds them: 100500 |
Nothing about these objects changed compared with Day 7. Only the description changed: interface Employee { instead of type Employee = {.
Now vary the interface. Everything you learned about object types on Day 7 still works inside an interface: a property with ? after its name is optional, and a property marked readonly can be read but never assigned again. The interface can also be used as a parameter type, exactly like a type alias:
interface Employee {
readonly id: number;
name: string;
salary: number;
office?: string;
}
function describe(employee: Employee): string {
const office = employee.office ?? "remote";
return `#${employee.id} ${employee.name} (${office})`;
}
const ana: Employee = { id: 1, name: "Ana Reyes", salary: 52000, office: "Lima" };
const ben: Employee = { id: 2, name: "Ben Okafor", salary: 48500 };
console.log(describe(ana));
console.log(describe(ben));
ben.salary = 50000;
console.log(ben.salary);#1 Ana Reyes (Lima)
#2 Ben Okafor (remote)
50000
Line 14 leaves out office, which is allowed because of the ? on line 5. Inside describe, employee.office therefore has the type string | undefined, and line 9 uses Day 9’s ?? to put "remote" in place of undefined. Line 18 assigns a new salary, which is fine: salary is an ordinary property. Assigning to id would not be, because of readonly on line 2; the checker refuses it exactly as it did for readonly properties on Day 7.
Key idea
interface Name { property: type; ... } describes an object’s shape for the checker, like a type alias does. An
object annotated with the interface must have every property that is not optional, with the right types. Nothing
about an interface survives into the running program.
Watch out
Leaving out a required property. Every property without a ? is required, and the checker checks the whole object at once:
interface Employee {
name: string;
salary: number;
}
const cara: Employee = { name: "Cara Lind" };
console.log(cara.name);employee-missing.ts:6:7 - error TS2741: Property 'salary' is missing in type '{ name: string; }' but required in type 'Employee'.Read the message from the end: the object was supposed to be an Employee, which requires salary, but the object literal (whose type the checker writes out as { name: string; }) has no salary. Column 7 is cara, the variable being given the wrong object. Add salary: 47000 to the object, or make the property optional if an employee really can lack one, then fix or delete the file before your next check.
Pause and try
Question 1 · Tracing
Predict exactly what this program shows.
interface Ticket {
readonly code: string;
seat: string;
meal?: string;
}
const first: Ticket = { code: "AB12", seat: "4A", meal: "vegetarian" };
const second: Ticket = { code: "CD34", seat: "17C" };
console.log(first.meal ?? "no meal");
console.log(second.meal ?? "no meal");
second.seat = "17D";
console.log(`${second.code} ${second.seat}`);
console.log(typeof second.meal);Check your reasoning
vegetarian
no meal
CD34 17D
undefined- Line 10:
first.mealis"vegetarian", which is notnullorundefined, so??keeps it. - Line 11:
secondhas nomeal, sosecond.mealisundefinedand??gives"no meal". - Line 12:
seatis notreadonly, so the assignment is allowed, and line 13 shows the new seat with the unchanged code. - Line 14: an optional property that was never given has the value
undefined, andtypeof undefinedis"undefined".
Reread 10.1 Interfaces if any line differed.
Question 2 · Multiple choice
Which statement about interface Employee { name: string; salary: number; } is true?
- When
nodereaches the interface, it creates an empty employee object. - The checker uses it to check objects annotated
: Employee, andnodenever sees it. - It must end with
= { }so that the properties have starting values. - Both properties are optional until the object is created.
Check your reasoning
B. An interface is a description for the checker. It is stripped out before the program runs, so node never sees it and no object is created by it.
- A is wrong: an interface creates nothing. Objects are created by object literals such as
{ name: "Ana", salary: 52000 }. - C is wrong: an interface has no
=and holds no values, only property names and types. - D is wrong: a property is optional only when its name ends with
?. Both of these are required.
Reread 10.1 Interfaces if you chose differently.
10.2 Extending an Interface
A manager is an employee with something extra: a list of the people who report to them. You could write a second interface with name, salary, and reports, but then the two descriptions would repeat each other, and if Employee later gained a startDate, you would have to remember to add it to Manager too. Interfaces have a way to say “everything in that one, plus this”: the keyword extends.
interface Manager extends Employee {
reports: string[];
}
Manager now has three properties: name and salary, inherited from Employee, and its own reports. The interface after extends is called the base interface, and the new one extends it.
Worked example: A manager is an employee too
interface Employee {
name: string;
salary: number;
}
interface Manager extends Employee {
reports: string[];
}
function payslip(employee: Employee): string {
return `${employee.name}: $${(employee.salary / 12).toFixed(2)} a month`;
}
const ana: Employee = { name: "Ana Reyes", salary: 52000 };
const dev: Manager = { name: "Dev Patel", salary: 71000, reports: ["Ana Reyes", "Ben Okafor"] };
console.log(payslip(ana));
console.log(payslip(dev));
console.log(dev.reports.length);Ana Reyes: $4333.33 a month
Dev Patel: $5916.67 a month
2| Line | What happens |
|---|---|
| 6–8 | A Manager is everything an Employee is, plus reports |
| 15 | The object literal must supply all three properties, and it does |
| 17 | payslip wants an Employee; ana is one |
| 18 | payslip wants an Employee, and dev is a Manager. The checker accepts it: dev has a name and a salary |
| 19 | dev is still a Manager outside payslip, so reports is there to count |
Line 18 is the important one. The checker does not match on names; it matches on shape. payslip needs an object with a name string and a salary number, and every Manager has both, so a Manager can go anywhere an Employee is expected. The extra reports property does no harm; payslip just never looks at it.
Now vary it. An interface can extend more than one base interface, separated by commas, and an extended interface can itself be extended, making a chain:
interface Named {
name: string;
}
interface Dated {
year: number;
}
interface Album extends Named, Dated {
tracks: number;
}
interface LiveAlbum extends Album {
venue: string;
}
const show: LiveAlbum = { name: "Night Sessions", year: 2023, tracks: 14, venue: "Roxy" };
function label(item: Named): string {
return item.name.toUpperCase();
}
console.log(label(show));
console.log(`${show.year}: ${show.tracks} tracks at the ${show.venue}`);NIGHT SESSIONS
2023: 14 tracks at the Roxy
Album collects name from Named and year from Dated, and adds tracks; LiveAlbum takes all three and adds venue. The object on line 17 needs all four properties. On line 23, label asks only for a Named, and a LiveAlbum has a name, so it is accepted.
Key idea
interface B extends A { ... } gives B every property of A plus its own. Because the checker compares shapes,
a B can go anywhere an A is expected, but not the other way around: an A lacks the properties only B has.
Watch out
Expecting extends to work in both directions. A Manager can stand in for an Employee, but an Employee cannot stand in for a Manager:
interface Employee {
name: string;
salary: number;
}
interface Manager extends Employee {
reports: string[];
}
function teamSize(manager: Manager): number {
return manager.reports.length;
}
const ana: Employee = { name: "Ana Reyes", salary: 52000 };
console.log(teamSize(ana));manager-only.ts:15:22 - error TS2345: Argument of type 'Employee' is not assignable to parameter of type 'Manager'.
Property 'reports' is missing in type 'Employee' but required in type 'Manager'.The second line of the message says exactly what is missing. teamSize would read manager.reports.length, and ana has no reports, so the program would crash if it ran. The checker stops it first. Fix or delete the file before your next check.
Changing an inherited property’s type. An extending interface may add properties, but it cannot give an inherited property a type that clashes with the base:
interface Employee {
name: string;
salary: number;
}
interface Manager extends Employee {
salary: string;
reports: string[];
}
const dev: Manager = { name: "Dev Patel", salary: "71000", reports: [] };
console.log(dev.salary);extends-conflict.ts:6:11 - error TS2430: Interface 'Manager' incorrectly extends interface 'Employee'.
Types of property 'salary' are incompatible.
Type 'string' is not assignable to type 'number'.If Manager could have a string salary, then passing a Manager to payslip, which divides salary by 12, would no longer be safe, and the whole point of extends would be lost. Remove line 7, or fix the base interface if the type there was wrong, then fix or delete this file.
Pause and try
Question 3 · Tracing
Predict exactly what this program shows, and say why npx tsc accepts line 20.
interface Shape {
color: string;
}
interface Circle extends Shape {
radius: number;
}
function paint(shape: Shape): string {
return `a ${shape.color} shape`;
}
function area(circle: Circle): number {
return Math.round(3.14 * circle.radius ** 2);
}
const dot: Circle = { color: "red", radius: 2 };
const wall: Shape = { color: "white" };
console.log(paint(dot));
console.log(paint(wall));
console.log(area(dot));Check your reasoning
a red shape
a white shape
13- Line 20:
paintwants aShape, and aCirclehas acolor, so the checker accepts it: a red shape. - Line 21:
wallis a plainShape: a white shape. - Line 22:
areawants aCircle, anddotis one.2 ** 2is 4,3.14 * 4is 12.56, andMath.roundgives 13.
area(wall) would be rejected, because a Shape has no radius.
Reread 10.2 Extending an Interface if any line differed.
Question 4 · Multiple choice
Given interface Pet { name: string; }, interface Dog extends Pet { breed: string; }, function feed(pet: Pet): void, function walk(dog: Dog): void, a const pet: Pet, and a const dog: Dog, which call does npx tsc reject?
feed(dog)walk(dog)walk(pet)feed(pet)
Check your reasoning
C. walk needs a Dog, which has a breed, and a plain Pet has none: TS2345, with the second line Property 'breed' is missing in type 'Pet' but required in type 'Dog'.
- A is wrong: a
Doghas aname, which is allfeedneeds. The extrabreedis ignored. - B is wrong: the types match exactly.
- D is wrong: the types match exactly.
Reread 10.2 Extending an Interface if you chose differently.
10.3 interface or type?
You now have two ways to name an object’s shape. For a plain object shape, they are interchangeable: the checker treats interface Point { x: number; y: number; } and type Coordinate = { x: number; y: number } as the same shape, so a Point value can be stored in a Coordinate variable. The difference is what else each one can do.
interface Point {
x: number;
y: number;
}
type Coordinate = { x: number; y: number };
type Size = "small" | "medium" | "large";
type Pair = [string, number];
const a: Point = { x: 1, y: 2 };
const b: Coordinate = a;
const size: Size = "medium";
const entry: Pair = ["Ana", 3];
console.log(b.x + b.y);
console.log(size.length);
console.log(entry[0]);3
6
Ana
Line 12 stores a Point in a Coordinate without complaint: same shape, same type as far as the checker is concerned. Lines 8 and 9 show what only a type alias can do: name a union, from Day 9, and a tuple, from Day 6. In 10.4 you will add a third thing to that list, a function type. An interface describes objects only. Try to give it a union and the checker does not even get as far as checking types:
interface Size = "small" | "medium" | "large";
const chosen: Size = "small";
console.log(chosen);interface-union.ts:1:16 - error TS1005: '{' expected.
TS1005 is a grammar error: after interface Size, the only thing that may come next is {. Change interface to type and add =, or delete the file, before your next check.
| Can it… | interface |
type |
|---|---|---|
| describe an object shape | yes | yes |
| build on another shape | yes, with extends |
yes, with &, which this course skips |
| name a union, tuple, function type | no | yes |
| be declared twice with one name | yes: the two declarations merge, a quirk | no: the checker reports a duplicate |
The last row is worth knowing because it surprises people: writing interface Employee twice in one file silently combines the two property lists instead of reporting a mistake. A type alias with the same name twice is an error.
So which should you use? A rule of thumb that most TypeScript code follows:
- Use
interfacefor the shape of an object, especially one that other shapes will extend. - Use
typefor everything else: unions, literal types, tuples, and function types.
Both are fine for objects, and some teams write type everywhere. What matters is to pick one convention in a project and stick to it. From today on, this course uses interface for objects and type for the rest.
Key idea
For an object shape, interface and type are interchangeable. Only an interface can extends another; only a type
alias can name a union, a tuple, or a function type. Use interface for objects and type for everything else.
Pause and try
Question 5 · Multiple choice
Which of these can be named only with a type alias, not with an interface?
{ title: string; pages: number }"on" | "off"{ readonly id: number; label?: string }- An object shape that a second interface extends
Check your reasoning
B. A union is not an object shape, and an interface can describe only object shapes. type Switch = "on" | "off" is the way to name it.
- A is wrong: an object shape can be either an interface or a type alias.
- C is wrong:
readonlyand?work inside an interface exactly as inside a type alias. - D is wrong: being extended is the one thing an interface does that a type alias does not.
Reread 10.3 interface or type? if you chose differently.
10.4 Function Types
On Day 8 you gave every function a type for each parameter and a return type. Put together, those are the function’s own type, and you are about to need a way to write it down. The reason is that a function is a value, like a number or a string: it can be stored in a variable, kept in an object’s property, and, in 10.5, handed to another function. Wherever a value goes, the checker wants to know its type.
Worked example: A function is a value
function square(n: number): number {
return n * n;
}
const double = (n: number): number => n * 2;
const chosen = square;
console.log(chosen(4));
console.log(double(4));
console.log(typeof square);
console.log(typeof square(4));16
8
function
number| Line | What happens |
|---|---|
| 1–3 | A function declaration, as on Day 8 |
| 5 | An arrow function stored in double; you have done this since Day 8 |
| 7 | square without parentheses is the function itself, not a call. chosen now holds the same function |
| 8 | Calling chosen runs square’s body with n set to 4 |
| 10 | Day 2’s typeof reports "function": a function is one more kind of value |
| 11 | With parentheses, square(4) runs first and gives 16, so typeof sees a number |
Hover over chosen on line 7 and VS Code shows const chosen: (n: number) => number. That is the function’s type, worked out by the checker from the declaration on line 1.
(n: number) => number is a function type: a type that says what a function takes and what it gives back. It is written as the parameter list in parentheses, then =>, then the return type:
(parameter: type, parameter: type) => returnType
| Piece | What it is |
|---|---|
(parameter: type) |
The parameters, each with a type; the names are for reading only, the types are what is checked |
=> |
Separates parameters from the result, as in an arrow function |
returnType |
The type of the value the function gives back; void for a function that gives nothing back |
The arrow looks like Day 8’s arrow function, and that is on purpose, but do not mix them up. In an arrow function, what follows => is an expression to work out: (n: number) => n * 2. In a function type, what follows => is a type: (n: number) => number. One is a value; the other describes a value.
Like any type, a function type can be given a name with type, and then used as an annotation:
type Comparator = (a: number, b: number) => number;
const difference: Comparator = (a, b) => a - b;
const reversed: Comparator = (a, b) => b - a;
function describe(name: string, compare: Comparator): void {
const result = compare(3, 12);
console.log(`${name}: ${result}`);
}
describe("difference", difference);
describe("reversed", reversed);difference: -9
reversed: 9
Line 1 names the type. Lines 3 and 4 store two different functions of that type. Notice that their parameters (a, b) have no annotations: the checker reads the types from the Comparator on the left of the =, so a and b are numbers without you saying so. Both functions must give back a number, and both do. Line 6 then uses the type for a parameter: describe takes a name and any Comparator, calls it with 3 and 12 on line 7, and shows the result. Passing a function to a function is the subject of 10.5; here just notice that difference and reversed are passed by name, without parentheses, as values.
A function can also be stored in a property of an object, and an interface can describe such a property. There are two ways to write it:
interface Formatter {
label: string;
format: (amount: number) => string;
check(amount: number): boolean;
}
const dollars: Formatter = {
label: "US dollars",
format: (amount) => `$${amount.toFixed(2)}`,
check(amount) {
return amount >= 0;
},
};
console.log(dollars.label);
console.log(dollars.format(19.5));
console.log(dollars.check(-4));US dollars
$19.50
false
Line 3 gives format a function type, like any other property type. Line 4 says the same kind of thing in method shorthand: the name, the parameter list, a colon, and the return type, with no =>. Both describe a property that holds a function; the shorthand is just the usual way to write it when the function belongs to the object. The object on lines 7 to 13 supplies format as an arrow function and check in the matching shorthand, a name followed directly by its parameter list and body. Again the parameters need no annotations: the interface already gave them. Lines 16 and 17 call the two functions with a dot, just as you call text.toUpperCase(). Day 3 named a function that belongs to a value a method; now you can make your own.
Key idea
A function is a value, and (a: number, b: number) => number is its type: parameter types, =>, return type. Name
one with type, use it to annotate a variable, a property, or a parameter, and leave the annotations off the
parameters of a function that already has one: the checker takes them from the type.
Watch out
A function that gives back the wrong kind of value. A function stored under a function type must return what the type promises:
type Comparator = (a: number, b: number) => number;
const isPositive: Comparator = (a) => a > 0;
console.log(isPositive(5, 2));wrong-shape.ts:3:39 - error TS2322: Type 'boolean' is not assignable to type 'number'.Column 39 is a > 0, the body of the arrow function. A Comparator must give back a number, and a comparison gives a boolean, so the function does not fit the type. Notice what the checker did not complain about: the function takes one parameter where the type lists two. A function may ignore parameters it does not need, so taking fewer is allowed; what it returns is not negotiable. If you want a function that answers yes or no, give it a type whose return type is boolean. Fix or delete the file before your next check.
Pause and try
Question 6 · Tracing
Predict exactly what this program shows.
type Scale = (value: number) => number;
const half: Scale = (value) => value / 2;
const plusTen: Scale = (value) => value + 10;
let scale: Scale = half;
console.log(scale(30));
scale = plusTen;
console.log(scale(30));
console.log(half(plusTen(30)));Check your reasoning
15
40
20- Line 6:
scaleis aletholdinghalf, so line 7 works out30 / 2: 15. - Line 8: the variable is given a different function of the same type, so line 9 works out
30 + 10: 40. - Line 10: the inner call runs first,
plusTen(30)is 40, andhalf(40)is 20.
A variable with a function type can hold any function that fits the type, and calling the variable calls whichever function it holds right now.
Reread 10.4 Function Types if any line differed.
Question 7 · Multiple choice
Which value can be stored in let check: (text: string) => boolean?
(text) => text.length(text) => text.includes("a")(count: number) => count > 0"text".includes("a")
Check your reasoning
B. It takes a string and gives back a boolean, which is exactly what the type promises; text gets its type from the annotation.
- A is wrong:
text.lengthis a number, so this function returns the wrong type (TS2322). - C is wrong: its parameter is a number, but the type says the function will be called with a string.
- D is wrong: this is not a function at all. It is a call that has already happened, and its value is the boolean
true.
Reread 10.4 Function Types if you chose differently.
10.5 Passing Functions as Arguments
On Day 6 you wrote loops that walked an array and built a new one: double every price, round every price, square every number. Each of those loops was the same five lines, with only the step in the middle changed. Since a function is a value, you can write the loop once and pass the step in as an argument.
Worked example: One loop, many steps
function applyToAll(values: number[], transform: (n: number) => number): number[] {
const results: number[] = [];
for (const value of values) {
results.push(transform(value));
}
return results;
}
function square(n: number): number {
return n * n;
}
const prices = [4, 10, 25];
console.log(applyToAll(prices, square));
console.log(applyToAll(prices, (n) => n * 2));
console.log(applyToAll(prices, (n) => Math.round(n * 1.2)));
console.log(prices);[ 16, 100, 625 ]
[ 8, 20, 50 ]
[ 5, 12, 30 ]
[ 4, 10, 25 ]applyToAll takes an array and a function of type (n: number) => number. It makes an empty array, calls the function on each value, pushes each result, and returns the new array. Follow line 14:
| Step | What happens |
|---|---|
| 14 | applyToAll is called with prices and square; transform now holds square |
| 4 | First time round the loop, transform(4) runs square with n as 4: 16 |
| 4 | Second time, transform(10) is 100 |
| 4 | Third time, transform(25) is 625 |
| 6 | The new array [16, 100, 625] is returned and shown |
Line 15 does not bother naming the step: it writes an arrow function right where the argument goes. Its parameter n has no annotation, because the checker takes the type from transform’s type on line 1, as in 10.4. Line 16 passes a third step. Line 17 shows prices unchanged: applyToAll is a pure function in Day 8’s sense, because it only reads its arguments and builds something new.
A function passed to another function, to be called by it, is a callback: you hand it over, and the other function calls it back later, as many times as it likes. A function that takes a callback, or returns a function as 10.8 shows, is called a higher-order function. applyToAll is one.
Now vary the callback’s type. A callback does not have to give anything back; it can simply do something each time it is called:
function repeat(times: number, action: (i: number) => void): void {
for (let i = 1; i <= times; i++) {
action(i);
}
}
repeat(3, (i) => {
console.log(`Lap ${i}`);
});
let total = 0;
repeat(4, (i) => {
total = total + i;
});
console.log(total);Lap 1
Lap 2
Lap 3
10
repeat calls action with 1, 2, and up to times, and ignores any result, so the callback’s type has the return type void. The first callback shows a line each time. The second one, on lines 12 to 14, shows nothing but adds i to total, a variable declared outside the callback: 1 + 2 + 3 + 4 is 10. How a function reaches a variable outside itself is the subject of 10.7.
Day 11 teaches that every array comes with built-in methods that work exactly like applyToAll, taking a callback and calling it for each element. Writing one yourself today is what makes those methods easy to read tomorrow.
Key idea
A callback is a function passed as an argument; the receiving function calls it, often once per element. Declare the parameter with a function type, pass a function by name without parentheses or write an arrow function on the spot, and leave its parameters unannotated: the checker already knows their types.
Watch out
Calling the callback instead of passing it. Parentheses after a function’s name run it, and what gets passed is its result:
function applyToAll(values: number[], transform: (n: number) => number): number[] {
const results: number[] = [];
for (const value of values) {
results.push(transform(value));
}
return results;
}
const double = (n: number): number => n * 2;
console.log(applyToAll([1, 2, 3], double(3)));call-instead-of-pass.ts:11:35 - error TS2345: Argument of type 'number' is not assignable to parameter of type '(n: number) => number'.double(3) is worked out first and gives 6, so line 11 passes the number 6 where applyToAll wants a function. The message says so: a number is not a (n: number) => number. Pass double with no parentheses, and let applyToAll do the calling. Fix or delete the file before your next check.
Pause and try
Question 8 · Tracing
Predict exactly what this program shows.
function countWhere(words: string[], test: (word: string) => boolean): number {
let count = 0;
for (const word of words) {
if (test(word)) {
count++;
}
}
return count;
}
const words = ["apple", "fig", "banana", "kiwi", "plum"];
console.log(countWhere(words, (word) => word.length > 4));
console.log(countWhere(words, (word) => word.startsWith("p")));
console.log(countWhere(words, (word) => word.includes("i")));Check your reasoning
2
1
2countWhere calls test on each word and counts the words for which it gives true.
- Line 13: words longer than 4 characters are
"apple"and"banana": 2. - Line 14: only
"plum"starts withp;"apple"starts witha: 1. - Line 15:
"fig"and"kiwi"containi: 2.
Reread 10.5 Passing Functions as Arguments if any line differed.
Question 9 · Multiple choice
In apply-to-all.ts, when does square run as a result of line 14, applyToAll(prices, square)?
- Once, before
applyToAllstarts, so that its result can be passed in - Inside
applyToAll, once for each element, each time line 4 reachestransform(value) - Never: only its name is passed, so its body is not needed
- Once, after
applyToAllreturns, on the finished array
Check your reasoning
B. Passing square hands over the function itself, not a result. applyToAll then calls it through the name transform, once per element, three times for a three-element array.
- A is wrong: there are no parentheses after
squareon line 14, so nothing runs there. Calling it there would also need an argument, and would pass a number, not a function. - C is wrong: the body runs every time
transform(value)is reached. - D is wrong: by the time
applyToAllreturns, the results are already in the new array.
Reread 10.5 Passing Functions as Arguments if you chose differently.
10.6 Rest Parameters and Spread Arguments
Every function so far has had a fixed number of parameters. But some jobs take any number of values: add up two prices, or ten; announce an event with three guests, or none. You could make the caller build an array first, but sum(1, 2, 3) reads better than sum([1, 2, 3]), and some built-in functions already work this way.
A rest parameter collects every remaining argument into an array. It is written with three dots before the name, and its type is always an array type:
function sum(...values: number[]): number {
let total = 0;
for (const value of values) {
total = total + value;
}
return total;
}
console.log(sum());
console.log(sum(5));
console.log(sum(1, 2, 3, 4));0
5
10
Inside sum, values is an ordinary number[], so Day 5’s accumulator loop adds it up. Line 9 passes no arguments at all, so values is the empty array and the loop never runs: 0. Line 10 gives [5], and line 11 gives [1, 2, 3, 4]. The checker still checks each argument: sum(1, "2") would be rejected, because every element of values must be a number.
A rest parameter can follow ordinary parameters, which take the first arguments as usual, and then the rest parameter takes whatever is left:
function announce(event: string, ...guests: string[]): void {
console.log(`${event}: ${guests.length} guests`);
for (const [index, guest] of guests.entries()) {
console.log(` ${index + 1}. ${guest}`);
}
}
announce("Book club", "Ana", "Ben", "Cara");
announce("Quiet night");Book club: 3 guests
1. Ana
2. Ben
3. Cara
Quiet night: 0 guests
On line 8, event takes "Book club" and guests takes the other three, which the loop numbers with Day 6’s entries(). On line 9, event takes the only argument and guests is empty. Because the rest parameter takes “everything left,” it must be the last parameter.
Now the other direction. You have an array, and you want to pass its elements as separate arguments. Day 6’s spread operator did this inside square brackets, [...items], to spread an array into a new array. Inside a call’s parentheses, it spreads an array into the arguments; this is a spread argument:
function sum(...values: number[]): number {
let total = 0;
for (const value of values) {
total = total + value;
}
return total;
}
const scores = [88, 92, 79];
const empty: number[] = [];
console.log(sum(...scores));
console.log(sum(100, ...scores));
console.log(Math.max(...scores));
console.log(Math.min(...scores));
console.log(Math.max(...empty));259
359
92
79
-Infinity
| Line | Call | Arguments the function receives | Result |
|---|---|---|---|
| 12 | sum(...scores) |
88, 92, 79 |
259 |
| 13 | sum(100, ...scores) |
100, 88, 92, 79 |
359 |
| 14 | Math.max(...scores) |
88, 92, 79 |
92 |
| 15 | Math.min(...scores) |
88, 92, 79 |
79 |
| 16 | Math.max(...empty) |
nothing | -Infinity |
Math.max and Math.min are built-in functions with rest parameters: they take any number of numbers and give back the largest or smallest. Spreading an array into them is the usual way to find the largest value in an array. Line 16 is the trap: with no arguments at all, Math.max gives -Infinity, the number below every other number, and Math.min gives Infinity. Neither is an error, so check length before you spread an array that might be empty.
Key idea
...values: number[] as the last parameter collects every remaining argument into an array. f(...items) spreads an
array out into separate arguments. Rest gathers; spread scatters.
Watch out
A rest parameter that is not last. The checker rejects it before it reads anything else:
function label(...parts: string[], separator: string): string {
return parts.join(separator);
}
console.log(label("a", "b", "-"));rest-not-last.ts:1:16 - error TS1014: A rest parameter must be last in a parameter list.
rest-not-last.ts:5:29 - error TS2554: Expected 2 arguments, but got 3.If parts took “everything left,” nothing would ever be left for separator. The second message follows from the first: the checker has fallen back to treating the function as having two ordinary parameters. Move separator to the front: function label(separator: string, ...parts: string[]). Fix or delete the file before your next check.
Spreading an array into fixed parameters. area wants exactly two numbers, and the checker cannot tell how many elements a number[] has:
function area(width: number, height: number): number {
return width * height;
}
const sides = [3, 4];
console.log(area(...sides));spread-array.ts:6:18 - error TS2556: A spread argument must either have a tuple type or be passed to a rest parameter.sides could hold one number or ten, so the checker cannot promise that area gets its two. The message names both fixes: spread into a rest parameter, which accepts any number, or make the array a tuple from Day 6, whose length the checker knows:
function area(width: number, height: number): number {
return width * height;
}
const sides: [number, number] = [3, 4];
console.log(area(...sides));12[number, number] has exactly two elements, so spreading it fills exactly two parameters. If you typed spread-array.ts, fix or delete it now.
Pause and try
Question 10 · Tracing
Predict exactly what this program shows.
function longest(first: string, ...rest: string[]): string {
let winner = first;
for (const word of rest) {
if (word.length > winner.length) {
winner = word;
}
}
return winner;
}
const fruit = ["fig", "banana", "kiwi"];
console.log(longest("pear"));
console.log(longest("pear", ...fruit));
console.log(longest("watermelon", ...fruit));
console.log(longest("a", "bb", "cc"));Check your reasoning
pear
banana
watermelon
bb- Line 13:
firstis"pear"andrestis empty, so the loop never runs and the winner is pear. - Line 14:
restis["fig", "banana", "kiwi"]."fig"is shorter than"pear";"banana"(6) is longer and becomes the winner;"kiwi"(4) is not longer than 6: banana. - Line 15:
"watermelon"has 10 characters and nothing inrestbeats it: watermelon. - Line 16:
"bb"beats"a", and"cc"is not longer than"bb", so the earlier word stays: bb.
Reread 10.6 Rest Parameters and Spread Arguments if any line differed.
Question 11 · Multiple choice
Given function join(separator: string, ...parts: string[]): string and const words = ["a", "b"], which call does npx tsc reject?
join("-")join("-", "a", "b")join(...words)join("-", ...words)
Check your reasoning
C. words is a string[] of unknown length, and the first element would have to fill the fixed parameter separator. The checker cannot promise there is one: TS2556.
- A is wrong: a rest parameter may receive nothing, so
partsis simply empty. - B is wrong:
separatortakes"-"andpartstakes the other two. - D is wrong: the spread goes into the rest parameter, which accepts any number of strings.
Reread 10.6 Rest Parameters and Spread Arguments if you chose differently.
10.7 Closures
Look back at repeat.ts. The second callback added to total, a variable declared outside it on line 11, and the final console.log saw the change. Day 8 said a variable declared inside a function stays inside it. The other direction is different: a function can use any variable that was in scope at the place where the function was written.
The simplest case is a function that uses a variable declared at the top of the file:
let clicks = 0;
function recordClick(): void {
clicks = clicks + 1;
console.log(`Clicks so far: ${clicks}`);
}
recordClick();
recordClick();
recordClick();
console.log(clicks);Clicks so far: 1
Clicks so far: 2
Clicks so far: 3
3
clicks is declared on line 1, outside every function, so every function in the file can see it. recordClick reads it and assigns it on line 4, and because there is only one clicks, each call carries on from where the last one left off. Line 11, outside the function, sees the final value too.
Now put a function inside another function. The inner function can use the outer function’s parameters and variables:
function countLongerThan(words: string[], limit: number): number {
function isLong(word: string): boolean {
return word.length > limit;
}
let count = 0;
for (const word of words) {
if (isLong(word)) {
count++;
}
}
return count;
}
const words = ["tea", "coffee", "water", "juice"];
console.log(countLongerThan(words, 3));
console.log(countLongerThan(words, 5));3
1
isLong is declared inside countLongerThan, so it can use limit, which is a parameter of the outer function. On line 16, limit is 3, and "coffee", "water", and "juice" are longer: 3. On line 17, a new call of countLongerThan starts, with its own limit of 5, and the isLong written during that call sees that limit: only "coffee" is longer: 1. The inner function is invisible outside countLongerThan, because it was declared inside its block, as Day 4 taught for blocks.
So far the outer variable was always still alive when the inner function ran. Here is the surprising part. What if the outer function returns the inner one, and finishes?
Worked example: A function that remembers
function makeGreeter(greeting: string): (name: string) => string {
return (name) => `${greeting}, ${name}!`;
}
const hello = makeGreeter("Hello");
const hola = makeGreeter("Hola");
console.log(hello("Ana"));
console.log(hola("Ana"));
console.log(hello("Ben"));Hello, Ana!
Hola, Ana!
Hello, Ben!| Line | What happens |
|---|---|
| 5 | makeGreeter("Hello") runs: greeting is "Hello", line 2 makes an arrow function that uses it, and returns it |
| 6 | A second call: a new greeting, "Hola", and a new arrow function that uses that one |
| 8 | hello("Ana") runs the first arrow function. makeGreeter finished long ago, yet greeting is still "Hello" |
| 9 | hola("Ana") runs the second one, which remembers "Hola" |
| 10 | hello still remembers "Hello"; nothing has changed it |
On Day 8 you learned that a function’s parameters and local variables are made when the function is called. The rule you did not yet know is when they go away: as long as some function still uses them, they stay. The arrow function returned on line 2 uses greeting, so the greeting from that call stays alive inside it. Each call of makeGreeter makes its own greeting and its own arrow function, so hello and hola remember different words.
A function together with the variables it remembers from the place it was written is called a closure. Every function in TypeScript is a closure; the word matters when the function outlives the scope it was written in, as hello outlived its call of makeGreeter. Picture it as a backpack: when a function is created, it packs up every outer variable it mentions, and it carries that backpack wherever it is passed or returned.
| Closure | Remembers |
|---|---|
hello |
greeting = "Hello" |
hola |
greeting = "Hola" |
Key idea
A function can use every variable that was in scope where it was written, and those variables stay alive as long as the function does, even after the function that made them has returned. A function plus the variables it remembers is a closure; each call of the outer function makes a fresh set.
Watch out
Expecting a closure to copy the value. A closure remembers the variable, not the value it had when the function was written:
let price = 10;
const showPrice = (): void => {
console.log(`Price: ${price}`);
};
showPrice();
price = 12;
showPrice();Price: 10
Price: 12People often predict Price: 10 twice, reasoning that showPrice was created while price was 10. But the arrow function holds a connection to the variable price itself, and reads its current value each time it runs. Line 8 changes the variable, so line 9 shows 12. The same rule is why recordClick and repeat.ts’s callback could change an outer variable and have the change stick. If you want a snapshot, pass the value in as an argument, or store it in a const of your own inside the function.
Pause and try
Question 12 · Tracing
Predict exactly what this program shows. Keep track of each closure’s used separately.
function makeTagger(tag: string): (text: string) => string {
let used = 0;
return (text) => {
used++;
return `[${tag} ${used}] ${text}`;
};
}
const todo = makeTagger("TODO");
const note = makeTagger("NOTE");
console.log(todo("buy milk"));
console.log(todo("call Ben"));
console.log(note("done"));
console.log(todo("walk"));Check your reasoning
[TODO 1] buy milk
[TODO 2] call Ben
[NOTE 1] done
[TODO 3] walkEach call of makeTagger makes its own tag and its own used, and the returned function remembers both.
| Line | Closure | used before |
used after |
Shown |
|---|---|---|---|---|
| 12 | todo |
0 | 1 | [TODO 1] buy milk |
| 13 | todo |
1 | 2 | [TODO 2] call Ben |
| 14 | note |
0 | 1 | [NOTE 1] done |
| 15 | todo |
2 | 3 | [TODO 3] walk |
note has its own used, which starts at 0, so line 14 shows 1, and todo’s count is untouched by it.
Reread 10.7 Closures if any line differed.
10.8 Functions That Return Functions
makeGreeter was a function whose job is to make functions. This is a common pattern with a name of its own: a factory function is a function that builds and returns a new function (or an object of functions) each time it is called. The thing to get right is its return type, which is a function type from 10.4.
Worked example: A multiplier factory
function makeMultiplier(factor: number): (n: number) => number {
return (n) => n * factor;
}
const double = makeMultiplier(2);
const triple = makeMultiplier(3);
console.log(double(7));
console.log(triple(7));
console.log(makeMultiplier(10)(7));
console.log(typeof double);14
21
70
functionLine 1’s return type, (n: number) => number, promises that makeMultiplier gives back a function that takes a number and returns a number. Line 2 returns an arrow function that fits: its n needs no annotation, because the return type already says n is a number, and the body uses factor, the closure’s remembered variable. Line 5 makes a function that remembers 2, and line 6 one that remembers 3; lines 8 and 9 call them. Line 10 has two pairs of parentheses: the first call, makeMultiplier(10), gives back a function, and the second pair calls that function with 7 straight away, without storing it: 70. Line 11 confirms that double is a function, not a number.
Now vary what is returned. makeGreeter and makeMultiplier remembered a value that never changed. A factory can also return several functions that share one remembered variable and change it, which gives you something new: a value that only those functions can touch.
interface Counter {
increment: () => number;
value: () => number;
}
function makeCounter(): Counter {
let count = 0;
return {
increment: () => {
count++;
return count;
},
value: () => count,
};
}
const clicks = makeCounter();
const visits = makeCounter();
clicks.increment();
clicks.increment();
visits.increment();
console.log(clicks.value());
console.log(visits.value());
console.log(clicks.increment());2
1
3
Lines 1 to 4 describe the result with an interface whose two properties hold functions, as in 10.4. makeCounter declares count on line 7 and returns an object whose increment adds one and gives back the new count, and whose value just gives back the count. Both arrow functions were written inside the same call, so they share the same count.
| Line | Call | clicks’s count |
visits’s count |
|---|---|---|---|
| 17 | makeCounter() |
0 | |
| 18 | makeCounter() |
0 | 0 |
| 20 | clicks.increment() |
1 | 0 |
| 21 | clicks.increment() |
2 | 0 |
| 22 | visits.increment() |
2 | 1 |
| 24 | clicks.value() |
2 | 1 |
| 25 | visits.value() |
2 | 1 |
| 26 | clicks.increment() |
3 | 1 |
Lines 17 and 18 call the factory twice, so there are two separate count variables, and the two counters never interfere. And nothing outside makeCounter can reach count directly: no line of the program can set it to 100 or to -5. The only ways in are the functions the factory handed out. A value that can be changed only through the functions that own it is called private state, and it is one of the most useful things closures give you. (Day 15 shows classes, which offer a dedicated syntax for the same idea.)
Key idea
A factory function returns a new function, or an object of functions, each time it is called. Its return type is a function type or an interface of function properties. Functions made in the same call share the variables of that call, which nothing outside can reach: private state.
Watch out
Reaching for the private variable from outside. It is not a property of the returned object, so the checker does not know it:
interface Counter {
increment: () => number;
value: () => number;
}
function makeCounter(): Counter {
let count = 0;
return {
increment: () => {
count++;
return count;
},
value: () => count,
};
}
const clicks = makeCounter();
clicks.count = 100;
console.log(clicks.value());counter-private.ts:18:8 - error TS2339: Property 'count' does not exist on type 'Counter'.count is a local variable inside a call of makeCounter, remembered by two closures. The returned object has only the two properties that Counter lists, so clicks.count does not exist. That is the design working as intended: if you want to change the count, call increment. Delete line 18, or delete the file, before your next check.
Pause and try
Question 13 · Tracing
Predict exactly what this program shows.
function makeAdder(amount: number): (n: number) => number {
return (n) => n + amount;
}
const addFive = makeAdder(5);
const addTen = makeAdder(10);
console.log(addFive(1));
console.log(addTen(addFive(1)));
console.log(makeAdder(-1)(0));Check your reasoning
6
16
-1- Line 8:
addFiveremembersamountas 5, soaddFive(1)is 6. - Line 9: inner call first,
addFive(1)is 6, thenaddTen(6)is 16. - Line 10:
makeAdder(-1)makes a function that subtracts 1, and the second pair of parentheses calls it with 0: -1.
Reread 10.8 Functions That Return Functions if any line differed.
Question 14 · Multiple choice
In make-multiplier.ts, what type does the checker give makeMultiplier(2)?
number(n: number) => numberfunctionvoid
Check your reasoning
B. makeMultiplier’s return type annotation on line 1 is (n: number) => number, so every call to it has that type. That is why double(7) is allowed on line 8.
- A is wrong:
numberis the type ofdouble(7), the result of calling the returned function, not of the function itself. - C is wrong:
"function"is what Day 2’stypeofreports at run time. The checker’s type is more precise: it says what the function takes and returns. - D is wrong:
voidmeans a function gives nothing back;makeMultipliergives back a function.
Reread 10.8 Functions That Return Functions if you chose differently.
Putting it together
A payroll report for a small team: an interface for employees and one that extends it for managers, a factory that makes a money formatter, a function with a rest parameter for totals, and a higher-order function that calls a callback for each team member. Before you type it, make sure npx tsc is clean in your day10 folder: fix or delete any broken file from today.
interface Employee {
name: string;
salary: number;
}
interface Manager extends Employee {
reports: string[];
}
type Member = Employee | Manager;
type Formatter = (amount: number) => string;
function makeFormatter(symbol: string): Formatter {
return (amount) => `${symbol}${amount.toFixed(2)}`;
}
function total(...amounts: number[]): number {
let sum = 0;
for (const amount of amounts) {
sum = sum + amount;
}
return sum;
}
function forEachMember(team: Member[], action: (member: Member) => void): void {
for (const member of team) {
action(member);
}
}
const dev: Manager = { name: "Dev Patel", salary: 71000, reports: ["Ana Reyes", "Ben Okafor"] };
const team: Member[] = [{ name: "Ana Reyes", salary: 52000 }, { name: "Ben Okafor", salary: 48500 }, dev];
const dollars = makeFormatter("$");
const salaries: number[] = [];
forEachMember(team, (member) => {
const role = "reports" in member ? `manager of ${member.reports.length}` : "employee";
console.log(`${member.name.padEnd(12)} ${dollars(member.salary / 12).padStart(10)} ${role}`);
salaries.push(member.salary);
});
console.log(`Payroll: ${dollars(total(...salaries))} a year`);npx tsc reports no errors, and node team-report.ts shows:
Ana Reyes $4333.33 employee
Ben Okafor $4041.67 employee
Dev Patel $5916.67 manager of 2
Payroll: $171500.00 a year
| Line | What happens | Idea |
|---|---|---|
| 1–8 | Manager has everything Employee has, plus reports |
10.1, 10.2 |
| 10–11 | A union of the two shapes, and a function type, both named with type |
10.3, 10.4 |
| 13–15 | A factory: the returned arrow function remembers symbol |
10.7, 10.8 |
| 17–23 | total collects any number of amounts into an array |
10.6 |
| 25–29 | A higher-order function that calls action once per member |
10.5 |
| 32 | A Manager can sit in a Member[], because it is an Employee | Manager |
10.2 |
| 34 | dollars is the function made by the factory; its type is Formatter |
10.8 |
| 37–41 | The callback is an arrow function written on the spot; it uses dollars and salaries from outside itself |
10.5, 10.7 |
| 38 | Day 9’s in narrows a Member to a Manager, so member.reports is allowed inside the first choice |
Day 9 |
| 39 | Day 6’s padEnd and Day 3’s padStart line up the columns |
Days 3, 6 |
| 43 | salaries is spread into total’s rest parameter, and the result goes through dollars |
10.6 |
Line 38 is the one place where the union on line 10 earns its keep: in narrows a Member to its Manager member, so member.reports is a string[]. With team typed as an Employee[], in would have no Manager to narrow to: the checker would give member.reports the type unknown, which Day 16 explains, and reject .length on it. The callback on lines 37 to 41 is a closure over dollars and salaries; it pushes into salaries each time it runs, and line 43 sees all three salaries afterwards. Add a fourth person to team and nothing else needs to change.
Common mistakes
Today’s messages in one place; the last row is a silent surprise.
| Message or symptom | Usual cause | Fix |
|---|---|---|
TS2741: Property 'salary' is missing in type ... but required in type ... |
An object literal lacks a required property | Add the property, or make it optional with ? |
TS2345: Argument of type 'Employee' is not assignable to parameter of type ... |
Passing the base shape where the extended one is needed | Pass an object that has the extra properties |
TS2430: Interface ... incorrectly extends interface ... |
Redeclaring an inherited property with a clashing type | Remove the redeclaration |
TS1005: '{' expected. after interface Name |
Giving an interface a union, tuple, or function type | Use type Name = ... |
TS2322: Type 'boolean' is not assignable to type 'number'. on a function body |
A function returns the wrong type for its function type | Return what the type promises |
TS2345: Argument of type 'number' is not assignable to parameter of type '(n: number) => number'. |
double(3) where double was meant: calling, not passing |
Drop the parentheses |
TS1014: A rest parameter must be last in a parameter list. |
A parameter after ...rest |
Move the rest parameter to the end |
TS2370: A rest parameter must be of an array type. |
...values: number instead of number[] |
Make the type an array type |
TS2556: A spread argument must either have a tuple type or be passed to a rest parameter. |
Spreading a number[] into fixed parameters |
Use a tuple, or a rest parameter |
TS2339: Property 'count' does not exist on type 'Counter'. |
Reaching for a closure’s private variable from outside | Call the functions the factory returned |
| A closure shows a newer value than expected | Expecting a snapshot; the closure reads the variable’s current value | Pass the value in as an argument |
Vocabulary
| Term | Definition | Example |
|---|---|---|
| interface | A named description of an object’s shape for the checker | interface Employee { name: string; } |
| extends | Gives an interface every property of a base interface plus its own | interface Manager extends Employee |
| base interface | The interface that another one extends | Employee |
| function type | The type of a function: parameter types, =>, return type |
(a: number, b: number) => number |
| method shorthand | Writing a function property as name(params): type in an interface or object |
check(amount: number): boolean; |
| callback | A function passed to another function, which calls it | applyToAll(prices, square) |
| higher-order function | A function that takes a function as an argument or returns one | applyToAll, makeCounter |
| rest parameter | ...name: type[] as the last parameter; collects the remaining arguments into an array |
function sum(...values: number[]) |
| spread argument | ...array inside a call; passes the elements as separate arguments |
Math.max(...scores) |
| closure | A function together with the variables it remembers from where it was written | The function makeGreeter returns |
| factory function | A function that builds and returns a new function or object of functions each call | makeCounter() |
| private state | A variable that only the functions made alongside it can reach | count inside makeCounter |
Summary
- An interface describes an object’s shape like a type alias does, and
extendsbuilds one interface on another. The checker compares shapes, so an extended interface’s object can go wherever the base is expected, but not the reverse. - Use
interfacefor objects andtypefor unions, tuples, and function types such as(n: number) => number. A function is a value with a type, and a variable, property, or parameter can hold one. - A callback is a function passed as an argument; the receiving function calls it, once per element in a loop or whenever it needs to. Pass the name without parentheses, and leave the callback’s parameters unannotated.
- A rest parameter,
...values: number[], gathers any number of arguments into an array and must come last; a spread argument,f(...items), scatters an array into separate arguments.Math.max()with nothing gives-Infinity. - A closure remembers the variables around it, as variables rather than snapshots, for as long as it lives. A factory function returns a new closure, or an object of closures sharing private state, on each call.
Practice
Do these in your day10 folder. First make sure npx tsc prints nothing there: if any broken file from today is still in the folder (such as employee-missing.ts, manager-only.ts, extends-conflict.ts, interface-union.ts, wrong-shape.ts, call-instead-of-pass.ts, rest-not-last.ts, spread-array.ts, or counter-private.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 starting values and run them again.
Question 15 · Short answer
Apply twice. Write applyTwice(fn, value), which takes a function of type (n: number) => number and a number, and returns the result of applying the function twice: fn(fn(value)). Call it with a named arrow function, with an arrow function written on the spot, and with Math.round.
Check your reasoning
One possible solution:
function applyTwice(fn: (n: number) => number, value: number): number {
return fn(fn(value));
}
const double = (n: number): number => n * 2;
const addThree = (n: number): number => n + 3;
console.log(applyTwice(double, 5));
console.log(applyTwice(addThree, 5));
console.log(applyTwice((n) => n * n, 3));
console.log(applyTwice(Math.round, 2.5));20
11
81
3The parameter fn has a function type, so applyTwice can call it; fn(value) runs first, and its result goes into the second call. double twice on 5 is 10 then 20; addThree twice is 8 then 11; squaring 3 twice is 9 then 81. Math.round is a built-in function of the right type, 2.5 rounds to 3, and rounding 3 again leaves it at 3.
Reread 10.5 Passing Functions as Arguments if your result differed.
Question 16 · Short answer
Counter factory. Write makeCounter(), which returns an object with three functions, increment, decrement, and value, that all share one private count. Describe the object with an interface. Make two counters and show that they count separately. Bonus: let the factory take an optional starting value.
Check your reasoning
One possible solution:
interface Counter {
increment: () => number;
decrement: () => number;
value: () => number;
}
function makeCounter(start = 0): Counter {
let count = start;
return {
increment: () => {
count++;
return count;
},
decrement: () => {
count--;
return count;
},
value: () => count,
};
}
const score = makeCounter();
const lives = makeCounter(3);
score.increment();
score.increment();
score.decrement();
lives.decrement();
console.log(`Score: ${score.value()}`);
console.log(`Lives: ${lives.value()}`);
console.log(score.increment());Score: 1
Lives: 2
2The three arrow functions are written in the same call of makeCounter, so they share that call’s count. score starts at 0 and goes up, up, down: 1. lives starts at 3, because of Day 8’s default parameter, and goes down once: 2. Line 32 increments score again and shows the value increment returns, 2, and no line can change count except through these three functions.
Reread 10.8 Functions That Return Functions if your result differed.
Question 17 · Short answer
Employees and managers. Define an Employee interface with a name and a salary, and a Manager interface that extends it with a list of reports. Write one function that accepts either, prints the name and salary, and prints the reports only for a manager. Call it with one of each.
Check your reasoning
One possible solution:
interface Employee {
name: string;
salary: number;
}
interface Manager extends Employee {
reports: string[];
}
function describe(person: Employee | Manager): void {
console.log(`${person.name} earns $${person.salary}`);
if ("reports" in person) {
console.log(` manages: ${person.reports.join(", ")}`);
}
}
const ana: Employee = { name: "Ana Reyes", salary: 52000 };
const dev: Manager = { name: "Dev Patel", salary: 71000, reports: ["Ana Reyes", "Ben Okafor"] };
describe(ana);
describe(dev);Ana Reyes earns $52000
Dev Patel earns $71000
manages: Ana Reyes, Ben OkaforThe parameter’s type is the union Employee | Manager, so Day 9’s in can narrow it: inside the if, the checker knows person is a Manager and allows person.reports. Declaring the parameter as just Employee would also accept a Manager, as 10.2 showed, but then "reports" in person would not give the checker a second shape to narrow to: it would give person.reports the type unknown (Day 16), and npx tsc would reject the .join call on it.
Reread 10.2 Extending an Interface if your result differed.
Review questions
Question 18 · Tracing
Predict exactly what this program shows. The return type on line 1 is an object type written out in full, with two function-typed properties.
function makeBank(opening: number): { deposit: (amount: number) => number; balance: () => number } {
let total = opening;
return {
deposit: (amount) => {
total = total + amount;
return total;
},
balance: () => total,
};
}
const savings = makeBank(100);
const spending = makeBank(20);
savings.deposit(50);
spending.deposit(5);
spending.deposit(5);
console.log(savings.balance());
console.log(spending.balance());
console.log(savings.deposit(0));Check your reasoning
150
30
150| Line | Call | savings’s total |
spending’s total |
|---|---|---|---|
| 12 | makeBank(100) |
100 | |
| 13 | makeBank(20) |
100 | 20 |
| 15 | savings.deposit(50) |
150 | 20 |
| 16 | spending.deposit(5) |
150 | 25 |
| 17 | spending.deposit(5) |
150 | 30 |
| 21 | savings.deposit(0) |
150 | 30 |
Each call of makeBank makes its own total, starting from its own opening. Line 21 deposits nothing and shows the value deposit returns, which is the unchanged 150.
Reread 10.8 Functions That Return Functions and 10.7 Closures if any line differed.
Question 19 · Debugging
This function should average any number of scores. npx tsc rejects it with four messages. Find the one mistake that causes all four, explain the first message, and write the fix.
function average(...values: number): number {
let total = 0;
for (const value of values) {
total = total + value;
}
return total / values.length;
}
console.log(average(80, 90, 100));Check your reasoning
average-broken.ts:1:18 - error TS2370: A rest parameter must be of an array type.
average-broken.ts:3:23 - error TS2488: Type 'number' must have a '[Symbol.iterator]()' method that returns an iterator.
average-broken.ts:6:25 - error TS2339: Property 'length' does not exist on type 'number'.
average-broken.ts:9:21 - error TS2345: Argument of type '[number, number, number]' is not assignable to parameter of type 'number'.The rest parameter is typed number, a single number, but a rest parameter always collects its arguments into an array, so its type must be an array type. The first message says exactly that. The other three follow from it: with values believed to be a number, the checker cannot loop over it with for...of (line 3), finds no length on it (line 6), and sees three arguments where a number was expected (line 9). Adding [] after number on line 1 fixes all four:
function average(...values: number[]): number {
let total = 0;
for (const value of values) {
total = total + value;
}
return total / values.length;
}
console.log(average(80, 90, 100));90If you typed the original program, fix or delete it before you go on.
Reread 10.6 Rest Parameters and Spread Arguments if you missed it.
Question 20 · Tracing
Predict exactly what this program shows. The rest parameter’s type is an array of function types; the parentheses around (s: string) => string keep the [] from applying to just string.
function transform(text: string, ...steps: ((s: string) => string)[]): string {
let result = text;
for (const step of steps) {
result = step(result);
}
return result;
}
const shout = (s: string): string => s.toUpperCase();
const exclaim = (s: string): string => `${s}!`;
console.log(transform("hi"));
console.log(transform("hi", shout));
console.log(transform("hi", exclaim, shout));
console.log(transform("hi", shout, exclaim, exclaim));Check your reasoning
hi
HI
HI!
HI!!transform starts with text and runs each callback in steps on the result so far, in order.
- Line 12: no steps, so
resultstays hi. - Line 13:
shout("hi")is HI. - Line 14:
exclaimfirst gives"hi!", thenshoutgives HI!. - Line 15:
shoutgives"HI", thenexclaimtwice adds two marks: HI!!.
Order matters on line 14: shout then exclaim would give the same text, but only because ! has no upper case. With other steps, swapping the order changes the result.
Reread 10.6 Rest Parameters and Spread Arguments and 10.5 Passing Functions as Arguments if any line differed.
Question 21 · Multiple choice
A program declares interface Item { name: string; price: number; }, a const book = { name: "Atlas", price: 30, pages: 240 } with no annotation, and function show(item: Item): void. What does npx tsc say about show(book)?
- It accepts the call:
bookhas every propertyItemrequires, and the extrapagesis ignored. - It rejects it with TS2741, because
pagesis missing fromItem. - It rejects it because
bookwas not annotated: Item. - It rejects it because an object can only be passed to a function whose parameter is a type alias, not an interface.
Check your reasoning
A. The checker matches shapes, not names or annotations. book has a name string and a price number, so it fits Item; the extra property does no harm, just as a Manager’s reports did no harm to payslip.
- B is wrong: TS2741 reports a property that is missing from the object;
pagesis extra, not missing, andItemis the description, not the object. - C is wrong: an annotation is never required for a shape to match.
book’s inferred type has all the right properties. - D is wrong: type aliases and interfaces describe shapes the same way, and either can be a parameter’s type.
Reread 10.2 Extending an Interface and 10.3 interface or type? if you chose differently.
Question 22 · Tracing
Predict exactly what this program shows.
interface Product {
name: string;
price: number;
}
interface Perishable extends Product {
daysLeft: number;
}
type Discount = (item: Product | Perishable) => number;
const clearance: Discount = (item) => item.price / 2;
const fresh: Discount = (item) => ("daysLeft" in item && item.daysLeft <= 1 ? item.price * 0.2 : item.price);
const milk: Perishable = { name: "milk", price: 2, daysLeft: 1 };
const rice: Product = { name: "rice", price: 4 };
console.log(clearance(milk));
console.log(fresh(milk));
console.log(fresh(rice));Check your reasoning
1
0.4
4- Line 18:
clearancehalves any item’s price, andmilkis 2: 1. - Line 19:
milkis aPerishable, so"daysLeft" in itemistrue, the checker narrowsitemtoPerishable, anddaysLeft <= 1istrue:2 * 0.2is 0.4. - Line 20:
ricehas nodaysLeft, soingivesfalse,&&stops there, and the conditional operator gives the full price: 4.
Both functions have the type Discount, so either can be stored in a Discount variable or passed where one is expected, even though one of them never looks at daysLeft.
Reread 10.4 Function Types and 10.2 Extending an Interface if any line differed.
Question 23 · Short answer
Mia says: “In make-counter.ts, count is declared with let inside makeCounter, so it should be gone as soon as makeCounter returns on line 14. How can clicks.value() still read it on line 24, and why do clicks and visits not share it?”
Check your reasoning
Model answer: A local variable lives as long as some function still uses it. increment and value are closures written inside the call of makeCounter, and both mention count, so count stays alive inside them after makeCounter returns; calling clicks.value() reads that remembered variable. clicks and visits come from two separate calls of makeCounter, and each call makes a fresh count and a fresh pair of closures, so the two counters each remember their own variable.
A complete answer must:
- say that a closure keeps the variables it uses alive after the outer function returns,
- say that both returned functions were written in the same call, so they share one
count, and - say that each call of the factory creates a new
count, which is why the counters are independent.
Reread 10.7 Closures and 10.8 Functions That Return Functions if your reasoning differed.
Go further
The Handbook’s object types page covers interfaces and extending them in more detail, its functions page covers rest parameters and spread, and MDN explains closures with more examples: TypeScript Handbook: Object Types (the “Extending Types” part), TypeScript Handbook: More on Functions (the “Rest Parameters and Arguments” part), and MDN: Closures.
Reflection
Check each statement. If the answer is “not yet,” reread the linked subsection.
- I can describe an object with an interface, including optional and readonly properties. Reread
- I can extend an interface and say which direction a value can be passed in. Reread
- I can say when to use interface and when to use type. Reread
- I can write a function type and store a function in a variable or a property. Reread
- I can pass a function as a callback and say when it runs. Reread
- I can collect arguments with a rest parameter and spread an array into a call. Reread
- I can explain what a closure remembers and predict what it shows. Reread
- I can write a factory function with private state and give it the right return type. Reread