HomeChallengesRepsProblemsLeaderboardTake a challenge

Narrow before you touch

getItem takes an id or a name, and promises a MenuItem it does not always have: a cast hides the undefined, so priceLabel("egusi") crashes. Make every caller deal with "not found".

Intermediate8 min on the clock5 graded checks · 100 pointsTypes That Catch Bugs
Graded by running your code against real cases.

What you build

  • Type getItem(identifier: string | number): MenuItem | undefined
  • Match a name regardless of case
  • Remove the cast, without using ! instead
  • Make priceLabel return "Not on the menu" on a miss

Done means

The return type admits "not found", both branches and the miss work, and nothing overrides the checker.

How it is graded

Published in full, before you start — every point is one of these and there is nothing else. Each one runs your code; it is not a search for keywords.

  1. The return type is MenuItem | undefined+20Union types and narrowing
  2. Refuses getItem(true)+15Union types and narrowing
  3. Both branches and the miss+30Union types and narrowing
  4. No ! and no as+20Union types and narrowing
  5. The caller handles a miss+15Union types and narrowing

What it teaches

The rest of Types That Catch Bugs