TypeScript traps · Chapter 1 of 16

An as cast that lied

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

  • Part: Data from outside
  • 3 tasks
  • TypeScript
  • Free chapter

Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.

Why you need this

The compiler does push back on a cast that is plainly wrong. typecheck on a file check.ts holding just this line (trimmed):

const left = '4' as number;
check.ts:1:14 - error TS2352: Conversion of type 'string' to type 'number' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.

But a value whose type is unknown (or any, which is what res.json() gives) can be cast to anything at all. That is exactly where outside data lives: bodies from other servers, files, messages. So the cast that matters most is the one the compiler can never question.

The honest type for data from outside is unknown, and the way out of it is narrowing: checks the compiler understands, after which it knows the type for real.

function isStock(value: unknown): value is Stock {
  if (typeof value !== 'object' || value === null) return false;
  const v = value as Record<string, unknown>;
  return typeof v.item === 'string' && typeof v.left === 'number';
}

for (const text of ['{"item":"ginger","left":4}', '{"item":"ginger","qty":4}']) {
  const body: unknown = JSON.parse(text);
  if (isStock(body)) console.log(body.item, body.left + 1);
  else console.log('not stock:', text);
}
ginger 5
not stock: {"item":"ginger","qty":4}

Inside the if, the compiler knows body is a Stock, and this time it is true.

The lesson

By the end of this case

You can tell an as cast that lied from its symptoms, make it happen on purpose with a fake service, replace the cast with a real check at the boundary, and pin it down with a test that fails on the bug and passes on the fix.

The ticket

TAP-412: Every price on the menu says ₹undefined. Assigned to you by Kabir. Priority: high. Since: this morning.

Anjali, in the customers channel at 8:20 am: "The app's menu says ₹undefined next to every chai. A customer sent a screenshot: Masala chai ₹undefined, Bun maska ₹undefined. Two people tried to order anyway and the cart said Total ₹NaN. It was fine last night."

The app's log, from the morning's first orders:

08:00:02.118  menu  menu: 14 items
08:14:36.502  cart  order 4120: total ₹NaN, payment not started

Kabir: "The franchise team moved the menu service to v2 last night. Their changelog says prices now come in paise, in a field with a new name. Our code has said price: number for a year and tsc is still green, which is the interesting part. Reproduce it first, then fix it, then make sure it can never come back. You are in menu.ts."

What an as cast does

A year ago Tapri moved to TypeScript, and the compiler has caught a lot since. But types live only in the compiler. When the code runs, node strips them out, and as goes with them. An as cast is you telling the compiler "trust me, this is a Stock", and it does, without looking:

type Stock = { item: string; left: number };

const body: unknown = JSON.parse('{"item":"ginger","qty":4}');
const stock = body as Stock;
console.log(stock.left, stock.left + 1);
undefined NaN

typecheck on the same file prints No type errors. The data said qty, the type said left, and nobody compared them.

Making it happen on purpose

A bug you can only see in production is a bug you cannot fix with confidence. So you reproduce it first, every time: you replace the real menu service with a fake, a plain object with the same method names that answers whatever you decide. No server, no network, no waiting. Here, it answers the way v2 does.

A test that would have caught it

A guard test turns the repro into something that runs before every release. The lab has vitest, and runs .ts test files as they are: it names one test, expect checks a value, and rejects.toThrow() checks that a promise fails. Here leftOf takes the stock service as a value, so a test can hand it a fake:

it('gives the count the service sent', async () => {
  expect(await leftOf({ get: async () => 4 }, 'ginger')).toBe(4);
});

it('refuses a count sent as text', async () => {
  await expect(leftOf({ get: async () => '4' }, 'ginger')).rejects.toThrow();
});

Beside a leftOf that ends in return body as number, the first test passes and the second stops it (trimmed):

 × refuses a count sent as text 4ms
AssertionError: promise resolved "'4'" instead of rejecting

A good guard fails on the bug and passes on the fix, so it tests both sides: good data is accepted, bad data is refused.

Your turn

Three tasks, one file each. In repro.ts, put ₹undefined on the menu on purpose, and run it with node repro.ts in the case's folder. In menu.ts, replace the cast with parseMenu, a real check; typecheck shows any type errors. In menu.test.ts, write the guard: the check runs it beside the original code, the fix and a wrong fix that only renames the field in its cast. Then answer Kabir's interview question at the bottom of the case, in your own words.

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: put ₹undefined on the menu on purpose

    Write reproduce() in repro.ts. Build a fake menu service, an object whose get(path) resolves to a v2 body: { items: [{ id: 'masala-chai', name: 'Masala chai', price_paise: 4000 }] }. Load the menu with loadMenu(api) from menu.ts and resolve to priceTag of the first item.

    The check runs your reproduce() twice: beside the original menu.ts it must resolve to 'Masala chai ₹undefined' (the menu from the ticket), and beside a fixed menu.ts it must resolve to 'Masala chai ₹40'. So it must really load masala chai at 4000 paise, sent the v2 way. No real waiting: the fake answers straight away, and reproduce() must finish within 2 seconds.

  2. Task 2

    menu.ts: check the menu before you trust it

    Write and export parseMenu(body: unknown): MenuItem[] in menu.ts, and make loadMenu use it. parseMenu checks the body before it becomes a menu: body must be an object whose items is a list, and every item must have a string id, a string name and price_paise, a whole number of paise, 0 or more. It gives back { id, name, price } for each item, with price in rupees (4000 paise is 40, 3550 is 35.5). Anything else, a body or any one item, makes it throw an Error saying what is wrong.

    loadMenu(api) asks api.get('/v2/menu'), resolves to parseMenu's items and keeps the log line menu: <n> items. Keep MenuItem and priceTag as they are. The check uses its own menus, broken ones too, and also type-checks menu.ts: parseMenu's parameter must be unknown and it must return MenuItem[]. A new as cast with the v2 field names is not a fix.

  3. Task 3

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

    Write a vitest test file, menu.test.ts, that would have caught this bug before the menu service moved to v2. The check runs your file three times: beside the original menu.ts, where at least one test must fail; beside the fixed menu.ts, where every test must pass; and beside a wrong fix that casts to the v2 field names instead of checking them, where at least one test must fail.

    So test both sides with fake menu services, as in your repro: a good v2 menu loads with its prices in rupees, and a broken one (a price sent as text, or no price at all) is refused. No real waiting: each test must finish within 3 seconds.

What you will learn

  • repro.ts: put ₹undefined on the menu on purpose
  • menu.ts: check the menu before you trust it
  • menu.test.ts: a test that would have caught it

More in Data from outside

Build "An as cast that lied" 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.

Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.