TypeScript traps · Chapter 12 of 16

An overload that promised too much

Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: Objects
  • 3 tasks
  • TypeScript
  • In the all labs plan

The first 2 chapters of TypeScript traps are free. This one comes with the all labs plan.

Why you need this

Here is the same trap in a function, finding a rider's longest trip:

type Trip = { rider: string; minutes: number };

function longestTrip(trips: Trip[]): Trip {
  return trips.reduce((a, b) => (b.minutes > a.minutes ? b : a));
}

console.log(longestTrip([{ rider: 'Salma', minutes: 18 }, { rider: 'Arjun', minutes: 31 }]));
console.log(longestTrip([]));

Node prints the first answer, then stops (trimmed):

{ rider: 'Arjun', minutes: 31 }
file:///workspace/chapters/demo-reduce-without-start/trips.ts:4
  return trips.reduce((a, b) => (b.minutes > a.minutes ? b : a));
               ^

TypeError: Reduce of empty array with no initial value

The return type Trip says "there is always a longest trip", and the first overload agreed. Two fixes work together. A sum has a natural start, 0. A "best of" has none, so its honest return type is Trip | undefined, and then the compiler makes every caller handle the empty case. In a file trips2.ts whose longestTrip returns Trip | undefined, a caller that reads .rider straight away is refused:

trips2.ts:11:25 - error TS2532: Object is possibly 'undefined'.

A caller that says what to show instead compiles and runs:

console.log(`longest: ${longestTrip([])?.rider ?? 'no trips yet'}`);
const minutes: number[] = [];
console.log(minutes.reduce((sum, m) => sum + m, 0));
longest: no trips yet
0

What you build: 3 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    repro.ts: crash the day report on purpose

    Write reproduce() in repro.ts. Build a day with two outlets, in this order: Indiranagar, which sold { item: 'Masala chai', cups: 120 } and { item: 'Bun maska', cups: 45 }, and Whitefield, which sold nothing (an empty list). Call dayReport from day-report.ts with that day and resolve to Whitefield's line; if dayReport throws, catch the error and resolve to its message.

    The check runs your reproduce() twice: beside the original day-report.ts it must resolve to 'Reduce of empty array with no initial value' (the error from the ticket), and beside a fixed day-report.ts it must resolve to 'Whitefield: 0 cups, best seller: none'. So Whitefield must really be in the day with no sales. No real waiting: reproduce() must finish within 2 seconds.

  2. Task 2

    day-report.ts: make an empty day a normal day

    Fix day-report.ts so an outlet with no sales is a normal day. totalCups of no sales is 0. bestSeller gives the sale with the most cups (the first one on a tie) and undefined when there are no sales. outletLine gives '<outlet>: <cups> cups, best seller: <item>', with none as the item for an empty day: outletLine('Whitefield', []) is 'Whitefield: 0 cups, best seller: none'. dayReport gives one line per outlet, in order, the empty ones included, so one empty outlet never stops the others.

    Keep Sale, OutletDay, the line's wording and the log line day report: <n> outlets as they are. The check uses its own days, and also type-checks day-report.ts: bestSeller's return type must be Sale | undefined, and totalCups must still return a number. Catching the error and leaving the outlet out of the report is not a fix.

  3. Task 3

    day-report.test.ts: a test that would have caught it

    Write a vitest test file, day-report.test.ts, that would have caught this bug before Whitefield opened. The check runs your file twice: beside the original day-report.ts, where at least one test must fail, and beside the fixed day-report.ts, where every test must pass.

    So test both sides with outletLine or dayReport (every version has them): an outlet with sales gets its usual line, and an outlet with no sales gets '<outlet>: 0 cups, best seller: none'. No real waiting: each test must finish within 3 seconds.

What you will learn

  • repro.ts: crash the day report on purpose
  • day-report.ts: make an empty day a normal day
  • day-report.test.ts: a test that would have caught it

More in Objects

Build "An overload that promised too much" yourself

Tapri moved to TypeScript, and Kabir, its senior developer, keeps assigning you tickets. Each is a real trap interviews love to ask about. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.

The first 2 chapters of TypeScript traps are free. This one comes with the all labs plan.