Sikau

TypeScript · Day 7 · about 30 min

Project: Typed shopping cart

Interfaces and functions working together.

Types make big programs calm

Let's type a small shopping cart: items with quantities, adding items, and a total. Notice how the types document the code — and how mistakes can't sneak in.

Types first, then code

Typing a project like this is the everyday work of a TypeScript developer: describe the data, write honest signatures, and let the compiler point out every place the two disagree.

In typed projects, start by describing the data. Once CartItem exists, every function signature almost writes itself: adding takes a cart and returns a cart, totalling takes a cart and returns a number. The types become a plan you can check before writing any logic.

interface CartItem {
  name: string;
  price: number;
  qty: number;
}

function addItem(cart: CartItem[], name: string, price: number): CartItem[] { … }
function removeItem(cart: CartItem[], name: string): CartItem[] { … }
function total(cart: CartItem[]): number { … }

Notice the functions return a new cart instead of changing the one they receive. That style pairs beautifully with TypeScript: you can mark parameters readonly CartItem[] and the compiler will stop any accidental push or splice on the input.

The rest of this lesson

  • Letting the compiler helpexplain
  • Typed workfloworder
  • Spot the errorpredict
  • A typed totalfill
  • Build the cartchallenge
  • Badge quizquiz
  • Unit 1 complete!recap

Continue this lesson free — run real code in your browser

Continue with Google

See all 24 lessons of TypeScript