lecture 7 of 120 completed

Typed arrays and tuples

An array type says what every item is. A tuple also fixes how many items there are and what each position holds.

What you'll learn

  • How to type a list, and what TypeScript infers for one
  • When a row of test data needs a tuple
  • Two places where a list can still surprise you at run time

A test has a list of daily fees. One entry was typed with quotes.

const fees: number[] = [0.5, 1, "2"];
fees.ts(1,33): error TS2322: Type 'string' is not assignable to type 'number'.

number[] is an array type. It reads "a list where every item is a number". The compiler checks each item and points at the one that does not fit.

What TypeScript infers for a list

Without an annotation, TypeScript looks at the items.

const fees = [0.5, 1, 2];
const titles = ["Dune", "Emma"];

const firstFee: number = fees[0];
const firstTitle: string = titles[0];

Both lists hold one kind of value, so the types are number[] and string[].

A row of test data often mixes kinds: a title and then a number of copies.

const row = ["Dune", 3];
const title: string = row[0];
rows.ts(2,7): error TS2322: Type 'string | number' is not assignable to type 'string'.
  Type 'number' is not assignable to type 'string'.

TypeScript inferred a list where each item is text or a number. It did not remember that the text comes first. So row[0] could be either, and it will not go into a string.

A tuple fixes the positions

A tuple is a list with a fixed length, where each position has its own type.

const row: [string, number] = ["Dune", 3];
const title: string = row[0];
const copies: number = row[1];

[string, number] says: exactly two items, text first and a number second. Now row[0] is text and row[1] is a number.

The compiler also knows the length.

const row: [string, number] = ["Dune", 3];
console.log(row[2]);
rows.ts(2,17): error TS2493: Tuple type '[string, number]' of length '2' has no element at index '2'.

You can take a tuple apart with destructuring, and each name gets the right type.

const row: [string, number] = ["Dune", 3];
const [title, copies] = row;
console.log(title.toUpperCase() + " x" + (copies + 1));
DUNE x4

Where tuples appear in tests

The usual place is a table of cases for one test: an input and the result you expect. Each row is a tuple, and the table is a list of them. You write a list of tuples by putting [] after the tuple type.

const cases: [number, string][] = [
  [0, "No fee"],
  [3, "1.50 EUR"],
];

for (const [daysLate, expected] of cases) {
  console.log(daysLate + " days: " + expected);
}
0 days: No fee
3 days: 1.50 EUR

A tuple is good for two or three values. With more, positions become hard to read, and a reviewer will ask for objects with named fields.

A list of objects

Most test data is a list of objects. Put [] after the interface name.

interface Book {
  title: string;
  copies: number;
}

const books: Book[] = [
  { title: "Dune", copies: 3 },
  { title: "Emma", copies: 0 },
];

const dune = books.find((book) => book.title === "Dune");
console.log(dune.copies);
books.ts(12,13): error TS18048: 'dune' is possibly 'undefined'.

find gives the first matching item, or undefined when nothing matches. The compiler knows that, so the result has the type Book | undefined. Handle it as you did in lecture 6.

Two surprises at run time

An empty list needs an annotation. With const titles = [], TypeScript has no item to read. Write const titles: string[] = [], so every later push is checked.

Reading past the end is not reported. This compiles.

const titles: string[] = ["Dune"];
const second = titles[1];
console.log(second.toUpperCase());
TypeError: Cannot read properties of undefined (reading 'toUpperCase')

The type string[] does not record how many items there are. So TypeScript gives titles[1] the type string, and at run time the value is undefined. The wording of the error is from the engine in Node and Chrome. A tuple does not have this problem, because its length is part of its type.

Check the length of a list before you read an item by position, as you would in JavaScript.

Remember this

number[] types every item of a list. A tuple such as [string, number] also fixes the length and gives each position its own type. find may return undefined, and the compiler says so. Reading past the end of a plain list is not reported, so check the length yourself.

Reference: Tuple Types in the TypeScript Handbook.

now prove it

Reading is the setup. Solve this exercise in the editor. We check your code with the TypeScript compiler and list each type error.