TypeScript tuples, readonly, and optional chaining

A tuple type such as [string, number] describes an array with a fixed length and a known type at each position. It is handy for returning two values from a function and unpacking them with destructuring. A readonly array type, written readonly number[], forbids push, pop, and element assignment, which documents and enforces that a function will not change its input.

TypeScript
function minMax(values: readonly number[]): [number, number] {
  return [Math.min(...values), Math.max(...values)];
}

const [low, high] = minMax([4, 9, 2, 7]);
console.log(low, high);

interface Address {
  city?: string;
}
interface Person {
  name: string;
  address?: Address;
  nickname?: string;
  visits: number;
}

const people: Person[] = [
  { name: "Ada", address: { city: "London" }, nickname: "A", visits: 0 },
  { name: "Bo", visits: 3 },
];

for (const person of people) {
  const city = person.address?.city ?? "unknown";
  const label = person.nickname ?? person.name;
  const visits = person.visits || 10;
  const visitsKept = person.visits ?? 10;
  console.log(label + " / " + city + " / " + visits + " / " + visitsKept);
}
Read the full lesson