Skip to content
HopperHopper

Course navigation

Phase 3 · Real programsDay 14

Generics

  • About 70 minutes
  • 8 sections
  • Runnable TypeScript examples
  • Practice questions

Before you start

About 70 minutes

By the end you will be able to

  1. Write a generic function with a type parameter, and say what type the checker gives back for each call.
  2. Describe reusable shapes with generic type aliases and interfaces, and limit a type parameter with a constraint.
  3. Recognize the generics you already use, such as Array, Map, and Record, and read their type arguments.
  4. Build new object types from old ones with Partial, Required, Pick, Omit, and Readonly.

What to remember from earlier

Section 1 of 8

14.1 Why Generics

Before you start, set up a new project folder named day14 the way you have set up every day’s folder since 1.2, with TypeScript installed and the same tsconfig.json. Every program today is a single file in that folder: check it with npx tsc and run it with node.

Here is a small job that comes up in almost every program: give back the first element of an array, or undefined if the array is empty. On Day 8 you learned that every parameter needs a type, so you have to say what kind of array it is. For an array of numbers, that is easy. Then you need the same thing for an array of names, and you write it again:

first-copies.ts
function firstNumber(items: number[]): number | undefined {
  return items[0];
}

function firstString(items: string[]): string | undefined {
  return items[0];
}

console.log(firstNumber([72, 95, 58]));
console.log(firstString(["Ana", "Ben"]));
console.log(firstString([]));
72
Ana
undefined

The two functions have the same body, word for word. Only the types differ. Line 2 relies on Day 6’s rule that reading past the end of an array gives undefined, which is why the return types say number | undefined and string | undefined, and why the last line prints undefined for the empty array. Now imagine you also need it for booleans, for Book objects, for tuples: one copy per type, and every bug fixed in one copy has to be fixed in all the others.

The obvious way out is one function whose parameter accepts several types, using a union from Day 9. Try it:

first-union.ts
function firstOf(items: (string | number)[]): string | number | undefined {
  return items[0];
}

const name = firstOf(["Ana", "Ben"]) ?? "nobody";
console.log(name.toUpperCase());
first-union.ts:6:18 - error TS2339: Property 'toUpperCase' does not exist on type 'string | number'.

This time there is one function, but the caller pays for it. firstOf promises only “a string or a number”, so even though line 5 passed an array of names, name has the type string | number, and the checker refuses toUpperCase because a number does not have it. The function forgot what kind of array it was given. The information was there at the call (the array was all strings), but the return type threw it away. Fix or delete first-union.ts before your next check.

What you want is a way to say: “this function takes an array of some type, and gives back an element of that same type.” Not a fixed type, and not a union of a few, but a type that is filled in fresh at each call. That is what a generic is: code written with a placeholder for a type, so that one function or one type description works for many types without losing track of which one it is working with.

Key idea

Writing a function once per type duplicates code; widening the parameter to a union loses information, because the caller gets back the whole union. Generics solve both: one function, and every caller still gets back exactly the type it put in.

Pause and try

Question 1 · Multiple choice

In first-union.ts, line 5 passes ["Ana", "Ben"]. Why does the checker still reject name.toUpperCase()?

  1. The array is empty, so name is undefined
  2. The return type says string | number, and the checker uses the return type, not the values that were passed
  3. toUpperCase cannot be used inside console.log
  4. Unions are not allowed in parameter types
Check your reasoning

B. At a call, the checker gives the result the function’s declared return type. firstOf declared string | number | undefined, and ?? removes only the undefined, so name is string | number. A number has no toUpperCase, so the checker rejects the call, even though this particular array held only strings.

  • A is wrong: the array has two names, and ?? "nobody" already handles the undefined case.
  • C is wrong: any expression can appear inside console.log; the problem is the method call itself.
  • D is wrong: union parameter types are allowed, and line 1 type-checks without complaint.

Reread 14.1 Why Generics if you chose differently.

Section 2 of 8

14.2 Generic Functions

A parameter, from Day 8, is a name for a value that the caller supplies: function greet(name: string) works for any name, and name stands for whichever one is passed. A generic function adds a second kind of parameter, a name for a type that the caller supplies. You declare it in angle brackets between the function name and the parentheses:

function first<T>(items: T[]): T | undefined {
Part What it means
<T> Declares a type parameter named T: a placeholder for a type, chosen fresh at every call
items: T[] The parameter is an array whose elements are of type T
T | undefined The function gives back a value of that same type T, or undefined

T is just a name, like a parameter name. It is a convention to use a single capital letter, and T (for “type”) is the usual choice for the first one. Because T appears in both the parameter and the return type, it connects them: whatever type the elements have, the result has the same one. A function with at least one type parameter is called a generic function.

Worked example: One first function for every array

first-generic.ts
function first<T>(items: T[]): T | undefined {
  return items[0];
}

const score = first([72, 95, 58]);
const name = first(["Ana", "Ben"]);
const nobody = first<string>([]);

console.log(score, name, nobody);
console.log((score ?? 0).toFixed(1));
console.log((name ?? "nobody").toUpperCase());
console.log((nobody ?? "nobody").toUpperCase());
72 Ana undefined
72.0
ANA
NOBODY

The body on line 2 is the same as in 14.1; only the types changed. Now follow each call:

Line Call Checker decides T is Result type Value
5 first([72, 95, 58]) number number | undefined 72
6 first(["Ana", "Ben"]) string string | undefined "Ana"
7 first<string>([]) string (you said so) string | undefined undefined

On lines 5 and 6 you never wrote what T is. The checker looked at the argument, saw a number[], and worked out that T must be number. Working out a type parameter from the arguments is called inference, the same thing the checker did on Day 2 when let count = 0 gave count the type number. Hover over score in VS Code and it shows number | undefined, not a union with string: the function remembered.

So lines 10 and 11 are both allowed. After ?? removes undefined, score is a number, so toFixed works, and name is a string, so toUpperCase works. That is exactly what first-union.ts could not do.

Line 7 shows the other way to choose T: write it yourself in angle brackets after the function name, first<string>(...). The type written there is called a type argument, just as a value passed to a parameter is an argument. You need it here because an empty array [] holds no elements to learn from, the same reason Day 7 wrote new Map<string, number>() for an empty map. Once you write a type argument, the checker holds the call to it:

wrong-type-argument.ts
function first<T>(items: T[]): T | undefined {
  return items[0];
}

const score = first<number>(["Ana", "Ben"]);
console.log(score);
wrong-type-argument.ts:5:30 - error TS2322: Type 'string' is not assignable to type 'number'.
wrong-type-argument.ts:5:37 - error TS2322: Type 'string' is not assignable to type 'number'.

first<number> means “T is number for this call”, so items must be a number[], and each of the two strings is rejected (columns 30 and 37 are "Ana" and "Ben"). Most of the time you leave type arguments out and let inference do the work; write one when there is nothing to infer from, or when you want the checker to hold you to a type. Fix or delete this file.

Key idea

function name<T>(...) declares a type parameter T. Using T in both a parameter and the return type connects them, so each call gets back the type it passed in. The checker infers T from the arguments, or you can write it yourself: first<string>([]).

Watch out

Treating T as a particular type inside the function. Inside the body, T could be any type, because the caller decides. So you may only do with a T value what you could do with every type at once:

shout-generic.ts
function shout<T>(value: T): string {
  return value.toUpperCase();
}

console.log(shout("hello"));
shout-generic.ts:2:16 - error TS2339: Property 'toUpperCase' does not exist on type 'T'.

The writer meant strings, but shout(42) or shout(true) would also match <T>, and they have no toUpperCase. The checker cannot know which type will come, so it allows only what every type has. If a function only makes sense for strings, it is not generic: write value: string. If it makes sense for several types that share a property, 14.5 shows how to say so. Fix or delete this file.

Pause and try

Question 2 · Tracing

Predict exactly what this program shows, and give the type the checker infers for T at each of the four calls.

predict-generic.ts
function repeatItem<T>(item: T, times: number): T[] {
  const result: T[] = [];
  for (let i = 0; i < times; i++) {
    result.push(item);
  }
  return result;
}

const stars = repeatItem("*", 3);
const zeros = repeatItem(0, 4);
console.log(stars.join(""), zeros.length);
console.log(repeatItem(true, 2));
console.log(repeatItem("ha", 0));
Check your reasoning
*** 4
[ true, true ]
[]
Line Call T Result
9 repeatItem("*", 3) string ["*", "*", "*"], so stars is a string[]
10 repeatItem(0, 4) number [0, 0, 0, 0], a number[]
12 repeatItem(true, 2) boolean [true, true]
13 repeatItem("ha", 0) string []: the loop body never runs

stars.join("") glues three stars into ***, and zeros.length is 4. Line 2 declares result as a T[], so inside the function T is used as a type just like number would be.

Reread 14.2 Generic Functions if any line differed.

Question 3 · Multiple choice

With first from first-generic.ts, what type does the checker give answer in const answer = first([true, false]);?

  1. boolean
  2. boolean | undefined
  3. T | undefined
  4. true | undefined
Check your reasoning

B. The argument is a boolean[], so the checker infers T as boolean, and the return type T | undefined becomes boolean | undefined.

  • A is wrong: the return type keeps | undefined, because an empty array would give undefined.
  • C is wrong: T is only a placeholder inside the function; at a call it is replaced by the type that was inferred.
  • D is wrong: for an array literal, the checker infers the general type boolean[], not a literal type for one element.

Reread 14.2 Generic Functions if you chose differently.

Section 3 of 8

14.3 More Than One Type Parameter

On Day 11, map turned a number[] into a string[] when its callback returned a string. The type of the new array depended on the callback. How does a function’s type say that? One type parameter is not enough: the elements going in and the results coming out can be different types. So a function can declare several type parameters, separated by commas, just like several value parameters.

Worked example: Your own map

map-all.ts
function mapAll<T, U>(items: T[], transform: (item: T) => U): U[] {
  const result: U[] = [];
  for (const item of items) {
    result.push(transform(item));
  }
  return result;
}

const prices = [4, 10, 2.5];
const labels = mapAll(prices, (price) => `$${price.toFixed(2)}`);
const lengths = mapAll(["kiwi", "fig"], (word) => word.length);

console.log(labels);
console.log(lengths);
[ '$4.00', '$10.00', '$2.50' ]
[ 4, 3 ]

Line 1 declares two type parameters. T is the type of the elements that go in; U (the next letter, by convention) is the type that comes out. The callback type (item: T) => U, Day 10’s function type, connects them: it takes one element and gives back one result.

Line T inferred from U inferred from what the callback returns Result
10 prices, a number[] a template literal: string string[]
11 ["kiwi", "fig"] word.length: number number[]

The checker first learns T from the array, then uses it to type the callback’s parameter (that is why price.toFixed is allowed with no annotation, as in 11.2), then learns U from what the callback returns. This is, in a few lines, how the real map is typed.

Type parameters can also be used inside a tuple type from Day 6, and an arrow function from Day 8 can be generic too. For an arrow function, the angle brackets go just before the parentheses:

make-pair.ts
function makePair<A, B>(first: A, second: B): [A, B] {
  return [first, second];
}

const wrap = <T>(value: T): T[] => [value];

const entry = makePair("Ana", 92);
const flag = makePair(3, true);
const [name, score] = entry;

console.log(entry, flag);
console.log(name.toUpperCase(), score + 1);
console.log(wrap("solo"), wrap(7));
[ 'Ana', 92 ] [ 3, true ]
ANA 93
[ 'solo' ] [ 7 ]

makePair("Ana", 92) infers A as string and B as number, so entry has the type [string, number], and destructuring it on line 9 gives a name that is a string and a score that is a number. That is why line 12 can call toUpperCase on one and add 1 to the other. Line 5’s wrap is a generic arrow function: <T>(value: T): T[] => [value] puts any value in a one-element array of its own type.

Key idea

A function can declare several type parameters, such as <T, U>. Each one is inferred separately, and using them together in a callback type like (item: T) => U says exactly how the input type and the output type are related.

Watch out

Expecting one type parameter to accept two types. Each use of the same T must be the same type at a given call:

same-type.ts
function bothEqual<T>(a: T, b: T): boolean {
  return a === b;
}

console.log(bothEqual(1, 1));
console.log(bothEqual(1, "1"));
same-type.ts:6:26 - error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.

The checker infers T from the first argument, 1, so T is number for this call, and then "1" does not fit. This is the checker doing its job: a number is never === a string, which is why Day 4’s TS2367 rejects such a comparison written out directly. If two arguments really may differ, give them two type parameters. Fix or delete this file.

Pause and try

Question 4 · Tracing

Predict exactly what this program shows, and give the types the checker infers for A and B. (padEnd(5) pads a string with spaces on the right to 5 characters, as you met on Day 11.)

predict-two-params.ts
function zip<A, B>(left: A[], right: B[]): [A, B][] {
  const pairs: [A, B][] = [];
  const count = Math.min(left.length, right.length);
  for (let i = 0; i < count; i++) {
    pairs.push([left[i], right[i]]);
  }
  return pairs;
}

const rows = zip(["Ana", "Ben", "Chen"], [88, 74]);
console.log(rows.length);
for (const [name, score] of rows) {
  console.log(`${name.padEnd(5)}${score}`);
}
Check your reasoning
2
Ana  88
Ben  74

A is string (from the names) and B is number (from the scores), so rows is a [string, number][]. count is the smaller length, Math.min(3, 2), which is 2, so the loop pairs only the first two names; Chen has no score and is left out. In the for...of header, each tuple is destructured into a name (a string, which allows padEnd) and a score.

Reread 14.3 More Than One Type Parameter if any line differed.

Section 4 of 8

14.4 Generic Types and Interfaces

Functions are not the only things that repeat for different types. Day 7’s type aliases and Day 10’s interfaces describe shapes, and shapes repeat too: a labeled box holding a string, a labeled box holding a number, a labeled box holding an array. A type alias or an interface can take type parameters in the same angle brackets, after its name. The result is a generic type: a shape with a placeholder that is filled in each time you use it.

type Pair<A, B> = [A, B];

interface Box<T> {
  label: string;
  contents: T;
}

Pair<A, B> is a tuple of any two types. Box<T> is an object with a label that is always a string and contents of whatever type you choose. To use a generic type you must give it its type arguments, as you did with Record<string, number> on Day 7: Pair<string, number>, Box<number>, Box<string[]>.

Worked example: Boxes of different things

box.ts
type Pair<A, B> = [A, B];

interface Box<T> {
  label: string;
  contents: T;
}

const entry: Pair<string, number> = ["Ana", 92];
const lunch: Box<string[]> = { label: "Lunch", contents: ["apple", "bread"] };
const savings: Box<number> = { label: "Savings", contents: 120 };

function open<T>(box: Box<T>): T {
  console.log(`Opening ${box.label}...`);
  return box.contents;
}

const food = open(lunch);
const money = open(savings);
console.log(entry[0], food.length, money * 2);
Opening Lunch...
Opening Savings...
Ana 2 240
Line Type written What it means
8 Pair<string, number> the same as [string, number]
9 Box<string[]> { label: string; contents: string[] }
10 Box<number> { label: string; contents: number }
12 Box<T>, inside open<T> a box of whatever type this call is about

Lines 12 to 15 combine both ideas: a generic function whose parameter is a generic type. open(lunch) infers T as string[] from lunch’s type, so food is a string[] and food.length is allowed. open(savings) infers number, so money * 2 is allowed. One interface, one function, and every box keeps its own contents type.

A generic type can be used inside another type, too. Here a scored entry pairs any item with a number, and a generic function picks the best one:

scored.ts
type Scored<T> = { item: T; score: number };

function best<T>(entries: Scored<T>[]): T | undefined {
  let top: Scored<T> | undefined = undefined;
  for (const entry of entries) {
    if (top === undefined || entry.score > top.score) {
      top = entry;
    }
  }
  return top?.item;
}

const songs: Scored<string>[] = [
  { item: "Blue", score: 7 },
  { item: "Gold", score: 9 },
  { item: "Rain", score: 8 },
];
const years: Scored<number>[] = [
  { item: 1999, score: 3 },
  { item: 2024, score: 5 },
];

console.log(best(songs));
console.log(best(years));
console.log(best<string>([]));
Gold
2024
undefined

Scored<T> on line 1 describes “an item of some type, with a score”. best<T> takes a Scored<T>[] and gives back a T | undefined: the item from the highest score, not the whole entry. It uses Day 5’s “best so far” pattern, with top starting as undefined so that the first entry always wins the first comparison, and Day 9’s ?. on line 10 so that an empty list gives undefined instead of crashing. Called with songs, T is string; called with years, it is number.

Key idea

type Name<T> = ... and interface Name<T> { ... } declare generic types. Using one requires its type arguments, such as Box<number>, which fill in the placeholder everywhere it appears in the shape.

Watch out

Leaving out the type argument. A generic type is incomplete until it is told what T is:

box-no-argument.ts
interface Box<T> {
  label: string;
  contents: T;
}

const gift: Box = { label: "Gift", contents: "scarf" };
console.log(gift.contents);
box-no-argument.ts:6:13 - error TS2314: Generic type 'Box<T>' requires 1 type argument(s).

Box on its own does not say what contents holds. Write Box<string>. (A generic function call can leave out its type arguments, because the checker infers them from the arguments; a type annotation has no arguments to infer from.) Fix or delete this file.

Pause and try

Question 5 · Multiple choice

With interface Box<T> { label: string; contents: T }, which annotation correctly describes a box labeled "Prices" that holds an array of numbers?

  1. const prices: Box = { label: "Prices", contents: [3, 5] };
  2. const prices: Box<number> = { label: "Prices", contents: [3, 5] };
  3. const prices: Box<number[]> = { label: "Prices", contents: [3, 5] };
  4. const prices: Box<string, number[]> = { label: "Prices", contents: [3, 5] };
Check your reasoning

C. The type argument replaces T, and T is the type of contents. The contents are an array of numbers, so T must be number[].

  • A is wrong: Box without a type argument is rejected with TS2314.
  • B is wrong: Box<number> means contents: number, and [3, 5] is not a single number.
  • D is wrong: Box declares only one type parameter; the label is always a string and is not a type argument.

Reread 14.4 Generic Types and Interfaces if you chose differently.

Section 5 of 8

14.5 Constraints with extends

The Watch Out in 14.2 showed that inside a generic function, T could be anything, so you can only do what works for everything. But some functions need a little more. Picking the longer of two values needs .length, which strings and arrays both have, and numbers do not. Try it with a plain T:

longest-error.ts
function longest<T>(a: T, b: T): T {
  return a.length >= b.length ? a : b;
}

console.log(longest("cat", "horse"));
longest-error.ts:2:12 - error TS2339: Property 'length' does not exist on type 'T'.
longest-error.ts:2:24 - error TS2339: Property 'length' does not exist on type 'T'.

Both reads of .length are rejected, because some types have no length. You need to tell the checker: “T can be any type, as long as it has a length that is a number.” That is a constraint, written with the keyword extends after the type parameter:

function longest<T extends { length: number }>(a: T, b: T): T {

Read T extends { length: number } as “T is some type that has at least a numeric length property”. You met extends on Day 10, where interface Manager extends Employee meant “a Manager has everything an Employee has, and maybe more”. It means the same here: T must have everything { length: number } has, and may have more. Fix or delete longest-error.ts.

Worked example: Longest, for strings and arrays

longest.ts
function longest<T extends { length: number }>(a: T, b: T): T {
  return a.length >= b.length ? a : b;
}

const word = longest("cat", "horse");
const list = longest([1, 2, 3], [4]);

console.log(word.toUpperCase());
console.log(list);
HORSE
[ 1, 2, 3 ]

Inside the function, the constraint lets line 2 read a.length and b.length: whatever T turns out to be, it has one. At the calls:

Line Call T inferred Has a numeric length? Result type
5 longest("cat", "horse") string Yes string
6 longest([1, 2, 3], [4]) number[] Yes number[]

The result type is still the exact type that went in, so line 8 can call word.toUpperCase(). The constraint limited which types are allowed; it did not erase which one was used.

A type that does not meet the constraint is rejected at the call:

longest-number.ts
function longest<T extends { length: number }>(a: T, b: T): T {
  return a.length >= b.length ? a : b;
}

console.log(longest(10, 200));
longest-number.ts:5:21 - error TS2345: Argument of type 'number' is not assignable to parameter of type '{ length: number; }'.

Numbers have no length, so 10 does not fit. Fix or delete this file.

Why not skip the generic and write the parameter type as { length: number } directly? Because then the function would forget the real type, as in 14.1. The most common constraint in real programs shows this clearly: “any object with a numeric id”. Here is a sort-by-id function written without generics:

lost-type.ts
function sortById(items: { id: number }[]): { id: number }[] {
  return items.toSorted((a, b) => a.id - b.id);
}

const users = [
  { id: 3, name: "Chen" },
  { id: 1, name: "Ana" },
];
const sorted = sortById(users);
console.log(sorted[0].name);
lost-type.ts:10:23 - error TS2339: Property 'name' does not exist on type '{ id: number; }'.

The users really do have names, and toSorted really does return the user objects. But the return type promises only { id: number }[], so the caller can no longer see name. Fix or delete this file. The generic version keeps it:

sort-by-id.ts
function sortById<T extends { id: number }>(items: T[]): T[] {
  return items.toSorted((a, b) => a.id - b.id);
}

const users = [
  { id: 3, name: "Chen" },
  { id: 1, name: "Ana" },
  { id: 2, name: "Ben" },
];
const products = [
  { id: 20, title: "Lamp", price: 35 },
  { id: 10, title: "Mug", price: 8 },
];

const sortedUsers = sortById(users);
const sortedProducts = sortById(products);

console.log(sortedUsers.map((user) => user.name));
console.log(sortedProducts.map((product) => `${product.title} $${product.price}`));
[ 'Ana', 'Ben', 'Chen' ]
[ 'Mug $8', 'Lamp $35' ]

On line 15, T is inferred as { id: number; name: string }; on line 16, as { id: number; title: string; price: number }. Both have a numeric id, so both are allowed, and line 2 may use a.id. The return type T[] hands each caller back its own type, so line 18 can read user.name and line 19 product.price. One function sorts both kinds of object, using only the property they share.

Key idea

A constraint, <T extends Shape>, allows only types that have at least the properties in Shape. Inside the function you may use those properties; at the call, the result keeps the caller’s full type. A plain parameter of type Shape would accept the same values but give back only Shape.

Watch out

Passing something that does not meet the constraint. The message names the constraint, not T:

sort-by-id-tags.ts
function sortById<T extends { id: number }>(items: T[]): T[] {
  return items.toSorted((a, b) => a.id - b.id);
}

const tags = ["red", "blue"];
console.log(sortById(tags));
sort-by-id-tags.ts:6:22 - error TS2345: Argument of type 'string[]' is not assignable to parameter of type '{ id: number; }[]'.

Read it as “you passed an array of strings, but this function needs an array of things with an id”. The indented line under it in the terminal narrows it down: Type 'string' is not assignable to type '{ id: number; }'. The fix is to pass the right data, not to change the function. Fix or delete this file.

Pause and try

Question 6 · Tracing

Predict exactly what this program shows.

predict-constraint.ts
function totalLength<T extends { length: number }>(items: T[]): number {
  let total = 0;
  for (const item of items) {
    total += item.length;
  }
  return total;
}

console.log(totalLength(["to", "be", "or"]));
console.log(totalLength([[1, 2], [3], []]));
console.log(totalLength([]));
Check your reasoning
6
3
0
  • Line 9: T is string; the lengths are 2 + 2 + 2 = 6.
  • Line 10: T is number[]; the inner arrays have lengths 2, 1, and 0, so the total is 3.
  • Line 11: the array is empty, so the loop body never runs and total stays 0.

The constraint is what allows item.length on line 4.

Reread 14.5 Constraints with extends if any line differed.

Question 7 · Multiple choice

With function longest<T extends { length: number }>(a: T, b: T): T from longest.ts, which call does npx tsc reject?

  1. longest("a", "bc")
  2. longest([true], [false, true])
  3. longest(5, 50)
  4. longest("", "")
Check your reasoning

C. T would be number, and numbers have no length property, so 5 does not meet the constraint and the checker reports TS2345.

  • A and D are wrong: strings have a numeric length. Empty strings are fine; their length is 0.
  • B is wrong: T is boolean[], and every array has a length. The constraint is about the container’s length, not about what the elements are.

Reread 14.5 Constraints with extends if you chose differently.

Section 6 of 8

14.6 Built-in Generics You Already Use

You have been using generic types since Day 6 without the name. Every time you wrote angle brackets after a type, you were giving type arguments to a generic type that TypeScript itself declares:

You wrote The generic type Its type parameters mean
number[] Array<T> T: the element type
new Map<string, number>() Map<K, V> K: the key type; V: the value type
new Set<string>() Set<T> T: the element type
Record<string, number> Record<K, V> K: the key type; V: the value type

number[] is a shorter way to write Array<number>; the two mean exactly the same type, and you may see either in other people’s code and in VS Code’s hover text. Map and Set are generic for the same reason as Box in 14.4: a map of names to ages and a map of words to counts share every method, and only the key and value types differ.

Worked example: The familiar types, written as generics

built-in-generics.ts
const scores: Array<number> = [90, 85];
const sameScores: number[] = scores;

const ages = new Map<string, number>();
ages.set("Ana", 17);

const seen = new Set<string>(["red"]);
seen.add("blue");

const grades: Record<"math" | "art", number> = { math: 90, art: 85 };

console.log(sameScores.length, ages.get("Ana"), seen.size);
console.log(grades.math + grades.art);
2 17 2
175

Line 1 writes the array type the long way, and line 2 shows it is the same type: number[] accepts scores without complaint. Line 4 makes an empty Map<string, number>; as with first<string>([]) in 14.2, the type arguments are needed because there are no entries to infer from. Line 7 could have inferred Set<string> from ["red"], but writing it is allowed. And because these are generic types, the checker knows that ages.get("Ana") is a number | undefined and seen.size a number.

Line 10 shows something new about Record. Its key type does not have to be string: here it is a union of Day 9 literal types, "math" | "art". That means “an object with exactly these keys, each holding a number”, so the checker knows grades.math exists.

With literal keys, a Record becomes a checklist the checker enforces. Leave a key out, and it notices:

record-missing-key.ts
const grades: Record<"math" | "art", number> = { math: 90 };
console.log(grades.math);
record-missing-key.ts:1:7 - error TS2741: Property 'art' is missing in type '{ math: number; }' but required in type 'Record<"math" | "art", number>'.

Record<string, number> from Day 7 allows any keys at all, so it could never report a missing one. Use literal keys when you know the full list of keys in advance, and string when keys arrive while the program runs.

The type arguments also guard every method. Array<number> gives push a parameter of type number, so:

array-generic-error.ts
const scores: Array<number> = [90, 85];
scores.push("100");
console.log(scores);
array-generic-error.ts:2:13 - error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.

This is the same message you would get with number[], because it is the same type. Fix or delete both broken files.

One more built-in generic is coming soon. Some work takes time, such as reading a file or getting data from a website, and JavaScript represents a result that will arrive later with a value called a promise. Its type is generic: Promise<string> is a promise of a string, Promise<Book[]> a promise of a list of books. You will read and write promises on Day 17; for now, recognize Promise<T> as “a T, eventually”, and read its type argument the way you read Array<T>’s.

Key idea

Array<T> (written T[]), Map<K, V>, Set<T>, and Record<K, V> are generic types built into TypeScript, and the angle brackets you have been writing are their type arguments. A Record with literal keys requires every key. Promise<T>, coming on Day 17, is a T that arrives later.

Pause and try

Question 8 · Multiple choice

const lists = new Map<string, number[]>(); is followed by const found = lists.get("Ana");. What type does the checker give found?

  1. number[]
  2. number[] | undefined
  3. string | undefined
  4. Map<string, number[]>
Check your reasoning

B. For a Map<K, V>, get takes a key of type K and gives back a value of type V, or undefined when the key is not there (Day 7). Here V is number[], so found is number[] | undefined, and you must narrow it before calling, say, found.length.

  • A is wrong: it forgets that the key might be missing.
  • C is wrong: string is the key type K; get gives back values, not keys.
  • D is wrong: that is the type of lists itself, not of one value in it.

Reread 14.6 Built-in Generics You Already Use if you chose differently.

Section 7 of 8

14.7 Partial and Required

A program often needs a type that is almost one it already has. A form for a new book starts empty and fills in one field at a time, so for a while it has some of a Book’s properties but not all. A list of changes to a user names only the properties that change. You could write a second alias with a ? on every property, but then the two types must be kept in step by hand: add a property to Book, forget the copy, and the checker never notices.

TypeScript has generic types that build a new object type from an old one. They are called utility types, and you use them like Box<T>: give the old type as the type argument. The first is Partial<T>: the same properties as T, but every one of them optional, exactly as if you had put a ? after each key.

Worked example: A book form that fills in over time

partial-draft.ts
type Book = {
  title: string;
  author: string;
  pages: number;
};

const draft: Partial<Book> = { title: "Dune" };
draft.pages = 412;

console.log(draft);
console.log(draft.author ?? "(author not entered yet)");

const empty: Partial<Book> = {};
console.log(Object.keys(empty).length);
{ title: 'Dune', pages: 412 }
(author not entered yet)
0

Partial<Book> on line 7 means { title?: string; author?: string; pages?: number }. The literal has only a title, which is allowed. Line 8 adds pages, which is also allowed, because pages is a property of the type (an optional one). Line 11 reads author, which was never set, and Day 9’s ?? supplies a message. Line 13 shows that even {} is a valid Partial<Book>: nothing is required.

Because every property of a Partial might be missing, every read gives a T | undefined, with the same rule as Day 7’s optional properties:

partial-unchecked.ts
type Book = {
  title: string;
  author: string;
  pages: number;
};

const draft: Partial<Book> = { title: "Dune", pages: 412 };
console.log(draft.pages.toFixed(0));
partial-unchecked.ts:8:13 - error TS18048: 'draft.pages' is possibly 'undefined'.

The literal on line 7 did include pages, but the type says it might not, and the checker goes by the type. Narrow it first, or use ??. Fix or delete this file.

The most common use of Partial is a set of changes to apply to an object. For that you need one more piece of Day 7’s spread. { ...book } copies every property into a new object. You can keep writing after the spread, and later properties replace earlier ones with the same key:

spread-override.ts
const book = { title: "Dune", author: "Herbert", pages: 412 };

const longer = { ...book, pages: 500 };
const changes = { title: "Dune Messiah", pages: 256 };
const sequel = { ...book, ...changes };
const backwards = { ...changes, ...book };

console.log(longer);
console.log(sequel);
console.log(backwards);
console.log(book.pages);
{ title: 'Dune', author: 'Herbert', pages: 500 }
{ title: 'Dune Messiah', author: 'Herbert', pages: 256 }
{ title: 'Dune', pages: 412, author: 'Herbert' }
412
Line Written What happens
3 { ...book, pages: 500 } Copies all three properties, then pages: 500 replaces the copied 412
5 { ...book, ...changes } Copies book, then copies changes over it: its title and pages win
6 { ...changes, ...book } The other order: book is copied last, so all of book’s values win and the changes are lost
11 book.pages Still 412: every spread built a new object and left book alone

So { ...original, ...changes } means “the original, with these changes applied”, and the order matters: the changes must come second. With changes typed as Partial<Book>, that one expression updates any combination of properties.

The opposite utility type is Required<T>: the same properties as T, with every ? removed. It suits options that may be left out by the caller but must all be filled in before the work starts:

required-options.ts
type LabelOptions = {
  width?: number;
  fill?: string;
};

function withDefaults(options: LabelOptions): Required<LabelOptions> {
  return {
    width: options.width ?? 10,
    fill: options.fill ?? ".",
  };
}

function label(text: string, options: LabelOptions): string {
  const settings = withDefaults(options);
  return text.padEnd(settings.width, settings.fill);
}

console.log(`[${label("Tea", {})}]`);
console.log(`[${label("Coffee", { width: 8 })}]`);
console.log(`[${label("Milk", { fill: "-", width: 6 })}]`);
[Tea.......]
[Coffee..]
[Milk--]

The caller passes LabelOptions, where both properties are optional. withDefaults on line 6 promises to give back a Required<LabelOptions>, so it must supply every property, and ?? fills each missing one with a default. Inside label, settings.width is a plain number, not number | undefined, so line 15 can pass it to padEnd with no checks. If withDefaults forgot a property, the checker would say so:

required-missing.ts
type LabelOptions = {
  width?: number;
  fill?: string;
};

const settings: Required<LabelOptions> = { width: 10 };
console.log(settings.width);
required-missing.ts:6:7 - error TS2741: Property 'fill' is missing in type '{ width: number; }' but required in type 'Required<LabelOptions>'.

Fix or delete this file.

Key idea

Partial<T> makes every property of T optional; Required<T> makes every property required. { ...original, ...changes } copies an object and then applies the changes, because later properties replace earlier ones.

Watch out

Spreading in the wrong order. { ...changes, ...original } type-checks and runs without a message, but it applies the changes first and then copies the whole original over them, so nothing changes (line 6 of spread-override.ts). Whatever should win goes last.

Pause and try

Question 9 · Tracing

Predict exactly what this program shows.

predict-partial.ts
type Player = {
  name: string;
  level: number;
  lives: number;
};

const start: Player = { name: "Ana", level: 1, lives: 3 };
const changes: Partial<Player> = { level: 2 };
const next = { ...start, ...changes, lives: start.lives - 1 };

console.log(next);
console.log(changes.lives ?? "no change", start.level);
Check your reasoning
{ name: 'Ana', level: 2, lives: 2 }
no change 1

Line 9 builds next in three steps: copy start (Ana, 1, 3); copy changes over it, which replaces level with 2; then lives: start.lives - 1, written last, replaces lives with 2. On line 12, changes has no lives, so changes.lives is undefined and ?? gives "no change". start.level is still 1: the spread made a new object.

Reread 14.7 Partial and Required if any line differed.

Section 8 of 8

14.8 Pick, Omit, and Readonly

Partial and Required keep every property and change whether it is optional. The next two choose which properties to keep. A user record includes a password, but the list of users you show on a page must not. A contact card needs only a name and an email. Each is a smaller version of User.

Pick<T, Keys> keeps only the listed properties of T. Omit<T, Keys> keeps every property except the listed ones. In both, Keys is one key name as a string literal type, or a union of them from Day 9: "name" | "email".

Worked example: Safe versions of a user

pick-omit.ts
type User = {
  id: number;
  name: string;
  email: string;
  password: string;
};

type Contact = Pick<User, "name" | "email">;
type PublicUser = Omit<User, "password">;

function toContact(user: User): Contact {
  return { name: user.name, email: user.email };
}

function toPublic(user: User): PublicUser {
  return { id: user.id, name: user.name, email: user.email };
}

const ana: User = { id: 1, name: "Ana", email: "ana@example.com", password: "tulip42" };

console.log(toContact(ana));
console.log(toPublic(ana));
{ name: 'Ana', email: 'ana@example.com' }
{ id: 1, name: 'Ana', email: 'ana@example.com' }
Line Type Same as
8 Pick<User, "name" | "email"> { name: string; email: string }
9 Omit<User, "password"> { id: number; name: string; email: string }

Use whichever makes the list shorter: Pick when you want a few properties of many, Omit when you want all but one or two. The functions on lines 11 and 15 build the smaller objects by copying the wanted properties one by one, and their return types make the checker confirm that the password never ends up in a PublicUser. And because both types are built from User, adding a phone property to User automatically adds it to PublicUser too.

A picked type really has only the picked properties:

pick-missing-key.ts
type User = {
  id: number;
  name: string;
  email: string;
  password: string;
};

type Contact = Pick<User, "name" | "email">;

const contact: Contact = { name: "Ana", email: "ana@example.com" };
console.log(contact.id);
pick-missing-key.ts:11:21 - error TS2339: Property 'id' does not exist on type 'Contact'.

Contact has a name and an email, nothing else, so there is no id to read. The checker also checks the key names you give Pick. Misspell one:

pick-typo.ts
type User = {
  id: number;
  name: string;
  email: string;
  password: string;
};

type Contact = Pick<User, "name" | "emial">;
pick-typo.ts:8:27 - error TS2344: Type '"name" | "emial"' does not satisfy the constraint 'keyof User'.

This message is a constraint from 14.5 at work. Pick is itself a generic type, declared with a constraint on its Keys parameter, and keyof User means “one of the key names of User”: "id" | "name" | "email" | "password". "emial" is not one of them. The indented line under it in the terminal even asks: Did you mean '"email"'? Fix or delete both files.

The last utility type is Readonly<T>: the same properties as T, with readonly in front of every one, as Day 7 did for a single property. Use it for objects that should never change after they are made:

readonly-book.ts
type Book = {
  title: string;
  pages: number;
};

const classic: Readonly<Book> = { title: "Emma", pages: 474 };
classic.pages = 500;
console.log(classic);
readonly-book.ts:7:9 - error TS2540: Cannot assign to 'pages' because it is a read-only property.

The message is the one Day 7 showed for a single readonly property. To “change” a read-only object, make a new one with a spread: { ...classic, pages: 500 }. Fix or delete this file.

Key idea

Pick<T, "a" | "b"> keeps only the listed properties; Omit<T, "c"> keeps all but the listed ones; Readonly<T> makes every property read-only. Key names are checked against the type, and building these types from the original keeps them in step with it.

Watch out

Expecting Readonly to protect what is inside a property. Readonly<T> stops you assigning to the object’s own properties. It does not reach into an array stored in one:

readonly-shallow.ts
type Playlist = {
  name: string;
  songs: string[];
};

const party: Readonly<Playlist> = { name: "Party", songs: ["Blue"] };
party.songs.push("Gold");

console.log(party);
{ name: 'Party', songs: [ 'Blue', 'Gold' ] }

party.songs = [] would be rejected, because that assigns to a property of party. But party.songs.push("Gold") does not assign to party at all; it changes the array that songs refers to, and that array is an ordinary string[]. So Readonly is shallow: it protects one level. To protect the array too, give it Day 6’s type readonly string[] in Playlist.

Pause and try

Question 10 · Tracing

Predict exactly what this program shows.

predict-utility.ts
type Order = {
  id: number;
  item: string;
  quantity: number;
  note?: string;
};

type OrderLine = Pick<Order, "item" | "quantity">;
type FullOrder = Required<Order>;

const line: OrderLine = { item: "Pen", quantity: 3 };
const full: FullOrder = { id: 7, item: "Mug", quantity: 1, note: "Gift wrap" };
const lines: OrderLine[] = [line, { item: full.item, quantity: full.quantity }];

console.log(lines.map((entry) => `${entry.quantity} x ${entry.item}`).join(", "));
console.log(Object.keys(full).length, Object.keys(line).length);
Check your reasoning
3 x Pen, 1 x Mug
4 2

OrderLine has only item and quantity. FullOrder is Required<Order>, so its literal must include note, which it does. Line 13 builds a second OrderLine from full’s item and quantity, and line 15 maps both lines to text and joins them. On line 16, full has four keys (id, item, quantity, note) and line has two.

Reread 14.8 Pick, Omit, and Readonly and 14.7 Partial and Required if any line differed.

Question 11 · Short answer

With type User = { id: number; name: string; email: string; password: string }, name the type you would write for each, using a utility type: (a) a user that can never be changed after it is made; (b) the changes a “settings” page may send, where any of the four properties may be included or left out; (c) a user for a public profile page, with everything but the password; (d) just the id and the name, for a drop-down list.

Check your reasoning

Model answer:

  • (a) Readonly<User>: every property becomes read-only.
  • (b) Partial<User>: every property becomes optional, so any combination is allowed.
  • (c) Omit<User, "password">: all but one property.
  • (d) Pick<User, "id" | "name">: just the two listed properties.

A complete answer chooses the utility type that matches each description and lists the right key names for (c) and (d). For (c), Pick<User, "id" | "name" | "email"> describes the same type, but Omit is shorter and stays right when User gains properties.

Reread 14.8 Pick, Omit, and Readonly and 14.7 Partial and Required if your answer differed.

Wrap-up · 1 of 7

Putting it together

A small task tracker counts tasks by owner and by status, finds the newest task, and prints a checklist. Before you type it, make sure npx tsc is clean in your day14 folder: fix or delete any broken file from today.

task-report.ts
type Task = {
  id: number;
  title: string;
  owner: string;
  done: boolean;
};

type TaskLine = Pick<Task, "title" | "done">;

function countBy<T>(items: T[], keyOf: (item: T) => string): Record<string, number> {
  const counts: Record<string, number> = {};
  for (const item of items) {
    const key = keyOf(item);
    counts[key] = (counts[key] ?? 0) + 1;
  }
  return counts;
}

function newest<T extends { id: number }>(items: T[]): T | undefined {
  return items.toSorted((a, b) => b.id - a.id)[0];
}

function toLine(task: Task): TaskLine {
  return { title: task.title, done: task.done };
}

const tasks: Readonly<Task>[] = [
  { id: 1, title: "Buy paint", owner: "Ana", done: true },
  { id: 4, title: "Fix gate", owner: "Ben", done: false },
  { id: 2, title: "Mow lawn", owner: "Ana", done: false },
];

console.log(countBy(tasks, (task) => task.owner));
console.log(countBy(tasks, (task) => (task.done ? "done" : "open")));
console.log(countBy(["red", "blue", "red"], (color) => color));

const latest = newest(tasks);
console.log(`Newest: ${latest?.title ?? "none"}`);

for (const line of tasks.map(toLine)) {
  console.log(`[${line.done ? "x" : " "}] ${line.title}`);
}

npx tsc reports no errors, and node task-report.ts shows:

{ Ana: 2, Ben: 1 }
{ done: 1, open: 2 }
{ red: 2, blue: 1 }
Newest: Fix gate
[x] Buy paint
[ ] Fix gate
[ ] Mow lawn
Lines What happens Idea
8 TaskLine is a Task with only title and done 14.8
10–17 countBy works for any element type T; the callback keyOf turns each element into a key, and the counts go into a Record 14.3, 14.6
19–21 newest needs only an id, so its constraint asks for no more, and it gives back the caller’s own type 14.5
27 Readonly<Task>[]: an array of tasks whose properties cannot be assigned 14.8
33–34 T is inferred as Readonly<Task>, so task.owner and task.done are allowed in the callbacks 14.2
35 The same countBy on a string[]: T is string 14.2
37–38 latest is Readonly<Task> | undefined, so ?. and ?? read its title safely; the newest is id 4 14.5
40–42 map(toLine) passes a named function as the callback (Day 10) and gives a TaskLine[] 14.8

countBy is written once and used three times, on two different element types. That is the payoff of today: a function general enough to reuse, and precise enough that every caller still knows exactly what it gets. Add a task with id 7 and run it again: the newest line and both counts change.

Wrap-up · 2 of 7

Vocabulary

Term Definition Example
generic Code written with a placeholder for a type, so it works for many types without losing track of which one function first<T>(items: T[])
type parameter The placeholder name for a type, declared in angle brackets T in <T>
generic function A function with at least one type parameter first<T>, mapAll<T, U>
inference The checker working out a type, here a type argument, from the values given first([1, 2]) infers T as number
type argument The actual type supplied for a type parameter string in first<string>([])
generic type A type alias or interface with type parameters interface Box<T>, Map<K, V>
constraint A rule, written with extends, that a type parameter must have certain properties <T extends { id: number }>
utility type A built-in generic type that builds a new object type from an existing one Partial<Book>, Omit<User, "password">
shallow Affecting only an object’s own properties, not the objects or arrays stored inside them Readonly<T>
Wrap-up · 3 of 7

Summary

  • A generic function declares a type parameter, <T>, and uses it to connect its parameters to its return type, so one function works for every type and each caller gets back exactly the type it passed in. The checker infers T from the arguments, or you write a type argument: first<string>([]).
  • Inside a generic function, T could be anything, so only what every type supports is allowed. A constraint, <T extends { length: number }>, allows more by accepting only types with those properties, while the result keeps the caller’s full type.
  • Type aliases and interfaces can be generic too (type Pair<A, B> = [A, B], interface Box<T>), and must be given their type arguments when used. Array<T>, Map<K, V>, Set<T>, and Record<K, V> are built-in generic types; Promise<T> comes on Day 17.
  • Utility types build new types from old ones: Partial and Required change whether properties are optional, Pick and Omit choose which properties to keep, and Readonly makes them all read-only, one level deep.
  • { ...original, ...changes } copies an object and applies changes, because later properties replace earlier ones.
Wrap-up · 4 of 7

Practice

Do these in your day14 folder. First make sure npx tsc prints nothing there: if any broken file from today is still in the folder (first-union.ts, wrong-type-argument.ts, shout-generic.ts, same-type.ts, box-no-argument.ts, longest-error.ts, longest-number.ts, lost-type.ts, sort-by-id-tags.ts, record-missing-key.ts, array-generic-error.ts, partial-unchecked.ts, required-missing.ts, pick-missing-key.ts, pick-typo.ts, or readonly-book.ts), fix it or delete it. Then write each program yourself, check it with npx tsc, run it with node, and only then open the answer. Hover over each result in VS Code to see the type the checker gave it.

Question 12 · Short answer

last and chunk. Write a generic last<T>(items: T[]): T | undefined that gives back the last element, and a generic chunk<T>(items: T[], size: number): T[][] that splits an array into smaller arrays of at most size elements each, in order. (T[][] is an array whose elements are T[] arrays.) Test both with an array of numbers and an array of strings, including an empty array and a size larger than the array.

Check your reasoning

One possible solution:

last-chunk.ts
function last<T>(items: T[]): T | undefined {
  return items[items.length - 1];
}

function chunk<T>(items: T[], size: number): T[][] {
  const chunks: T[][] = [];
  for (let start = 0; start < items.length; start += size) {
    chunks.push(items.slice(start, start + size));
  }
  return chunks;
}

const scores = [72, 95, 58, 88, 61];
const names = ["Ana", "Ben", "Chen", "Dev"];

console.log(last(scores), last(names), last<number>([]));
console.log(chunk(scores, 2));
console.log(chunk(names, 3));
console.log(chunk(names, 10));
61 Dev undefined
[ [ 72, 95 ], [ 58, 88 ], [ 61 ] ]
[ [ 'Ana', 'Ben', 'Chen' ], [ 'Dev' ] ]
[ [ 'Ana', 'Ben', 'Chen', 'Dev' ] ]

last reads index length - 1; for an empty array that is index -1, which gives undefined, as the return type promises. chunk steps start forward by size each time and copies items.slice(start, start + size) with Day 6’s slice, which stops at the end of the array on its own, so the last chunk may be shorter. Because both use T, chunk(scores, 2) is a number[][] and chunk(names, 3) a string[][]. Try chunk([], 2): the loop never runs, and the result is [].

Reread 14.2 Generic Functions if your result differed.

Question 13 · Short answer

findById. Write findById<T extends { id: number }>(items: T[], id: number): T | undefined, which gives back the first item with that id. Use it on an array of users (id, name) and an array of products (id, title, price), print a property that only users have and one that only products have, and handle an id that is not there.

Check your reasoning

One possible solution:

find-by-id.ts
type User = { id: number; name: string };
type Product = { id: number; title: string; price: number };

function findById<T extends { id: number }>(items: T[], id: number): T | undefined {
  for (const item of items) {
    if (item.id === id) {
      return item;
    }
  }
  return undefined;
}

const users: User[] = [
  { id: 1, name: "Ana" },
  { id: 2, name: "Ben" },
];
const products: Product[] = [
  { id: 10, title: "Mug", price: 8 },
  { id: 20, title: "Lamp", price: 35 },
];

const ben = findById(users, 2);
const lamp = findById(products, 20);
const missing = findById(users, 99);

console.log(ben?.name);
console.log(lamp ? `${lamp.title} costs $${lamp.price}` : "No such product");
console.log(missing?.name ?? "No user with id 99");
Ben
Lamp costs $35
No user with id 99

The constraint lets line 6 read item.id. At line 22, T is User, so ben is a User | undefined and ben?.name is allowed; at line 23, T is Product, so lamp.price is allowed once the conditional operator has checked that lamp is not undefined. Line 24 finds nothing, so ?? supplies the message. (Day 11’s find would also work as the body: return items.find((item) => item.id === id);.)

Reread 14.5 Constraints with extends if your result differed.

Question 14 · Short answer

updateUser. Define a User type with id, name, email, and age. Write updateUser(user: User, changes: Partial<User>): User, which gives back a new user with the changes applied and leaves the original untouched. Show a change to one property, a change to two, and an empty set of changes.

Check your reasoning

One possible solution:

update-user.ts
type User = {
  id: number;
  name: string;
  email: string;
  age: number;
};

function updateUser(user: User, changes: Partial<User>): User {
  return { ...user, ...changes };
}

const ana: User = { id: 1, name: "Ana", email: "ana@example.com", age: 17 };
const older = updateUser(ana, { age: 18 });
const moved = updateUser(older, { email: "ana.lee@example.com", name: "Ana Lee" });
const same = updateUser(ana, {});

console.log(older);
console.log(moved);
console.log(ana.age, same === ana);
{ id: 1, name: 'Ana', email: 'ana@example.com', age: 18 }
{ id: 1, name: 'Ana Lee', email: 'ana.lee@example.com', age: 18 }
17 false

Partial<User> lets the caller pass any combination of properties, including none. Line 9 copies the user and then the changes, so the changes win. The last line shows ana still has age 17, and that even with no changes the result is a new object (same === ana is false), so the function is pure in Day 8’s sense. One gap remains: Partial<User> also allows { id: 2 }. If ids must never change, type the parameter as Partial<Omit<User, "id">>: utility types can be combined, because each one’s result is an ordinary type.

Reread 14.7 Partial and Required if your result differed.

Wrap-up · 5 of 7

Review questions

Question 15 · Debugging

This function should count the items that are at least min long, for strings or arrays. npx tsc rejects it. Quote the message, explain it, and fix it.

review-count-error.ts
function countLong<T>(items: T[], min: number): number {
  return items.filter((item) => item.length >= min).length;
}

console.log(countLong(["kiwi", "fig", "banana"], 4));
Check your reasoning
review-count-error.ts:2:38 - error TS2339: Property 'length' does not exist on type 'T'.

T has no constraint, so it could be any type, including number or boolean, which have no length. The checker therefore refuses item.length. Add a constraint that says every allowed type has a numeric length:

review-count-fixed.ts
function countLong<T extends { length: number }>(items: T[], min: number): number {
  return items.filter((item) => item.length >= min).length;
}

console.log(countLong(["kiwi", "fig", "banana"], 4));
console.log(countLong([[1, 2, 3, 4], [5]], 4));
2
1

Now strings and arrays are both accepted: “kiwi” and “banana” are at least 4 long, and of the two arrays only [1, 2, 3, 4] is.

Reread 14.5 Constraints with extends if you missed it.

Question 16 · Debugging

applyChanges should switch the theme to dark. npx tsc accepts it, but the output is wrong. Predict what it shows, explain why, and fix it.

review-spread-order.ts
type Settings = {
  theme: string;
  fontSize: number;
};

function applyChanges(settings: Settings, changes: Partial<Settings>): Settings {
  return { ...changes, ...settings };
}

const current: Settings = { theme: "light", fontSize: 14 };
console.log(applyChanges(current, { theme: "dark" }));
Check your reasoning
{ theme: 'light', fontSize: 14 }

The spread copies changes first (theme: "dark") and then settings over it, and settings has its own theme: "light", which replaces the change. Later properties win, so whatever should win must come last:

review-spread-fixed.ts
type Settings = {
  theme: string;
  fontSize: number;
};

function applyChanges(settings: Settings, changes: Partial<Settings>): Settings {
  return { ...settings, ...changes };
}

const current: Settings = { theme: "light", fontSize: 14 };
console.log(applyChanges(current, { theme: "dark" }));
{ theme: 'dark', fontSize: 14 }

Nothing reports the original mistake, because both orders build a valid Settings.

Reread 14.7 Partial and Required if you missed it.

Question 17 · Tracing

Predict exactly what this program shows. Think about what contents holds in each box.

predict-box.ts
interface Box<T> {
  label: string;
  contents: T;
}

function relabel<T>(box: Box<T>, label: string): Box<T> {
  return { label: label, contents: box.contents };
}

const tools: Box<string[]> = { label: "Shed", contents: ["saw", "rake"] };
const moved = relabel(tools, "Garage");
moved.contents.push("hose");

console.log(moved.label, moved.contents.length);
console.log(tools.label, tools.contents.length);
Check your reasoning
Garage 3
Shed 3

relabel is generic, so T is string[] and moved is a Box<string[]>. It builds a new box object with a new label, but contents: box.contents copies only the reference to the array (Day 7), so both boxes share one array. push("hose") on line 12 changes that shared array, and both boxes report 3 tools. tools.label is still "Shed", because moved is a separate object. Generics change what the checker knows about types; they do not change how JavaScript copies values.

Reread 14.4 Generic Types and Interfaces if any line differed.

Question 18 · Short answer

Maya writes function cheapest(items: { price: number }[]): { price: number } | undefined and calls it on an array of products that also have a name. Explain why cheapest(products)?.name is rejected, and write the header that fixes it.

Check your reasoning

Model answer: The parameter accepts the products, because each has a price. But the return type says only { price: number }, so the result has forgotten every other property, and the checker reports TS2339: name does not exist on { price: number }. Make the function generic with a constraint, so the result keeps the caller’s type:

function cheapest<T extends { price: number }>(items: T[]): T | undefined {

Now T is inferred as the product type, the result is a product or undefined, and ?.name is allowed.

A complete answer says that the plain parameter type throws away the other properties, and uses a type parameter with an extends { price: number } constraint in both the parameter and the return type.

Reread 14.5 Constraints with extends if your answer differed.

Question 19 · Multiple choice

readonly-shallow.ts declared const party: Readonly<Playlist>, where Playlist is { name: string; songs: string[] }. Which of these lines does npx tsc accept?

  1. party.name = "Picnic";
  2. party.songs = ["Rain"];
  3. party.songs[0] = "Rain";
  4. None of them
Check your reasoning

C. Readonly is shallow: it makes name and songs read-only properties of party, but the array that songs refers to is an ordinary string[], and changing one of its elements does not assign to a property of party.

  • A and B are wrong: both assign to a property of party, and the checker reports TS2540.
  • D is wrong: C is allowed, which is exactly the gap the Watch Out in 14.8 described. Typing songs as readonly string[] would close it.

Reread 14.8 Pick, Omit, and Readonly if you chose differently.

Question 20 · Multiple choice

Which statement about type Totals = Record<"food" | "travel", number> is true?

  1. const t: Totals = { food: 20 }; is accepted, and t.travel is undefined
  2. const t: Totals = { food: 20, travel: 30 }; is accepted, and so is t.fees = 5; afterwards
  3. const t: Totals = { food: 20, travel: 30 }; is accepted, and t.food + t.travel is allowed
  4. Totals means the same as Record<string, number>
Check your reasoning

C. A Record with literal keys requires exactly those keys, each holding a number, so the full literal is accepted and both properties are known numbers.

  • A is wrong: a missing key is reported with TS2741, as in record-missing-key.ts.
  • B is wrong: fees is not one of the two keys, so the checker reports that the property does not exist.
  • D is wrong: Record<string, number> allows any key and requires none; the literal union is what makes the keys exact.

Reread 14.6 Built-in Generics You Already Use if you chose differently.

Wrap-up · 6 of 7

Go further

The TypeScript Handbook’s chapter on generics covers today’s ideas with more examples, including generic constraints that use one type parameter in another’s constraint: TypeScript Handbook: Generics. The Utility Types reference page lists every built-in utility type, of which today’s five are the most used.

Wrap-up · 7 of 7

Reflection

Check each statement. If the answer is “not yet,” reread the linked subsection.

  • I can explain why a union parameter loses information that a generic keeps. Reread
  • I can write a generic function and say what type each call gives back. Reread
  • I can use two type parameters, as in a callback type (item: T) => U. Reread
  • I can declare a generic type alias or interface and supply its type arguments. Reread
  • I can add a constraint with extends and explain why it beats a plain parameter type. Reread
  • I can read Array, Map, Set, and Record as generic types, including a Record with literal keys. Reread
  • I can use Partial and Required, and apply changes with a spread in the right order. Reread
  • I can build smaller or read-only types with Pick, Omit, and Readonly. Reread