HomeChallengesRepsProblemsLeaderboardTake a challenge

One function, any item

findMenuItem, findOrder and findCustomer are the same function three times. Write it once, with a generic that keeps each caller’s own type — and a constraint that refuses anything without an id.

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

What you build

  • Write findById<T extends { id: number }>(items: readonly T[], id: number): T | undefined
  • Write addToQueue<T>(queue: T[], item: T): T[], returning a new array
  • Replace all three finders with findById
  • Call addToQueue<Order>(...) with an explicit type argument once

Done means

One generic finder that keeps the caller’s type and enforces its constraint, used everywhere.

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. findById(menu, 1) is MenuItem | undefined+20Generics that keep the caller’s type
  2. Refuses items with no id+20Generics that keep the caller’s type
  3. An explicit type argument checks the item+15Generics that keep the caller’s type
  4. The three finders are gone+20Generics that keep the caller’s type
  5. One function, three types, same behaviour+25Generics that keep the caller’s type

What it teaches

Generics that keep the caller’s typeadvanced

A generic function takes its types as parameters, so one function serves menu items, orders and customers while handing each caller back its own type — where any would hand back nothing the compiler can check.

The rest of Types That Catch Bugs