Command Palette

Search for a command to run...

Hectal
Phase 10: Utility Types and Type-Level Patterns
TypeScript · Exercise 3 of 5 PreviousNext
Advanced

Stop Mixing Up Ids

A shop has cart ids and product ids, both numbers. Right now addToCart(cartId(2), cartId(1)) compiles: a cart id is passed where a product id belongs.

Turn ProductId and CartId into branded types, and make both constructor functions check that the number is a positive whole number (throw a RangeError otherwise). The checks use addToCart, productId and cartId.

What Check tests

  1. Your code has no type errors
  2. The console prints the cart line
  3. A bad id throws a RangeError
  4. A cart id can't be passed as a product id
  5. A plain number can't be passed as a cart id
  6. The right ids are accepted

Stuck? One hint at a time

The solution unlocks after your first Check. Try first: that is where the learning happens.

Runs in your browser. Your code is saved here.

Console

Nothing printed yet.