TypeScript traps · Chapter 13 of 16

this lost in a method passed as a callback

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

Passing a method as a callback does exactly that. Then the code that calls it decides this. Node's EventEmitter calls each listener with this set to the emitter. Here StockAlarm is a small class whose ring(left) pushes a line to this.rings (its code and the import are trimmed):

const shelf = new EventEmitter();
const alarm = new StockAlarm();
shelf.on('low', function (this: unknown) {
  console.log('this is the emitter:', this === shelf);
});
shelf.on('low', alarm.ring);
try {
  shelf.emit('low', 2);
} catch (error) {
  console.log((error as Error).message);
}
this is the emitter: true
Cannot read properties of undefined (reading 'push')

The emitter has no rings, so this.rings is undefined. TypeScript types a method's this as the class, and does not check what this a callback will really get: on accepts any function. You can declare a this parameter, ring(this: StockAlarm, left: number), and then a plain call ring(2) in a file thisparam.ts is refused:

thisparam.ts:13:1 - error TS2684: The 'this' context of type 'void' is not assignable to method's 'this' of type 'StockAlarm'.

But in that same file shelf.on('low', alarm.ring) and setTimeout(alarm.ring, 10, 2) still compile: their parameter types say nothing about this.

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: lose the printer on purpose

    Write reproduce() in repro.ts. Make a bus, a new EventEmitter from node:events, and a ReceiptPrinter for 'HSR Layout', and connect them with connectPrinter from printer.ts. Then emit one paid order on the bus: the event 'paid' with { id: 4501, total: 65 }. If the emit throws, catch the error and resolve to its message; if it does not, resolve to the printer's queue.

    The check runs your reproduce() twice: beside the original printer.ts it must resolve to "Cannot read properties of undefined (reading 'push')" (the error from the ticket), and beside a fixed printer.ts it must resolve to the queue, [{ id: 4501, total: 65 }]. So the order must really go through the bus. No real waiting: emit calls every listener straight away, and reproduce() must finish within 2 seconds.

  2. Task 2

    printer.ts: keep the printer when the bus calls it

    Fix connectPrinter(bus, printer) in printer.ts so that every 'paid' order emitted on a bus is queued on the printer connected to that bus. Each printer queues only its own bus's orders: two printers on two buses never get each other's orders. connectPrinter still returns a function that disconnects the printer: once it is called, that bus's orders are no longer queued, and other printers keep printing.

    Keep ReceiptPrinter as it is: its outlet, its queue, print (which still works when called on the printer directly) and the log line <outlet>: receipt for order <id> queued. The check uses its own outlets and orders, connects two printers to two buses at once and disconnects one, and also type-checks printer.ts. A variable that remembers the last printer connected is not a fix.

  3. Task 3

    printer.test.ts: a test that would have caught it

    Write a vitest test file, printer.test.ts, that would have caught this bug before the printer was connected to the bus. The check runs your file three times: beside the original printer.ts, where at least one test must fail; beside the fixed printer.ts, where every test must pass; and beside a wrong fix that remembers the last printer connected in one variable, where at least one test must fail.

    So connect printers to real EventEmitter buses and check their queues: one printer gets the order paid on its bus, and two printers on two buses each get only their own bus's orders. No real waiting: each test must finish within 3 seconds.

What you will learn

  • repro.ts: lose the printer on purpose
  • printer.ts: keep the printer when the bus calls it
  • printer.test.ts: a test that would have caught it

More in Objects

Build "this lost in a method passed as a callback" 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.