AI Hints
Home›TypeScript Tutorial›Cart Practice and Unions
TypeScript · Lesson 28 of 120

Practice: A Shopping Cart

Objects together.

⏱ 2 min read▶ Video at 22:01🎓 Free
Watch this lesson in the TypeScript courseWatch on YouTube ↗Full TypeScript course

Let's practise everything about objects. We'll build a small shopping cart, with typed items, a typed cart, and a function that totals it.

Practice: A Shopping Cart
From the video: Practice: A Shopping Cart
  • Typed items
  • A typed cart
  • A total

A typed cart

Cart item has a readonly product, a price, and a quantity. The cart has items, and an optional coupon. Total adds up each line, then takes ten percent off with the coupon. Run it.

app.tstypescript
interface CartItem {
  readonly product: string;
  price: number;
  quantity: number;
}

interface Cart {
  items: CartItem[];
  coupon?: string;
}

function total(cart: Cart): number {
  const sum = cart.items.reduce((s, i) => s + i.price * i.quantity, 0);
  return cart.coupon === "SAVE10" ? sum * 0.9 : sum;
}

const cart: Cart = { items: [{ product: "Helmet", price: 40, quantity: 2 }] };
console.log("Total:", total(cart));
console.log("With coupon:", total({ ...cart, coupon: "SAVE10" }));
Output
Total: 80
With coupon: 72

Summary

Interfaces, readonly, optional properties, and arrays work together to type a whole cart. Next, the objects quiz.

Key takeaways
  • CartItem
  • Cart
  • total()
Next up: Objects Quiz — test yourself