Patterns as words

Lesson 8 Types as a table of contents

6 min read · JavaScript · Quiz

read the types and signatures before the code

What you'll learn

  • Read signatures and field lists before reading any body
  • Say what an optional or nullable type asks of the caller
  • Find the places where a type is only a claim: casts, any and outside data

Before you read a function body, read its signature. In typed code, the types are a table of contents, and they cost you nothing.

The idea

A signature tells you what goes in, what comes out, and what can go wrong, without reading one line of the body. In TypeScript these are the parameter and return types. In Python they are type hints and dataclasses. Order | undefined or Order | None says "the caller must handle not found". Promise<...> says "this is async". A list of fields says what an order is.

But types are a claim, not a proof. TypeScript types vanish when the code runs, and Python never checks hints at all. A cast (as, **data) or any turns the checking off. So read the types first, then ask where they could be lying: data from outside, and casts.

order.ts (TypeScript)
1interface OrderLine {2  sku: string;3  qty: number;4  price: number;5}67interface Order {8  id: string;9  lines: OrderLine[];10  couponCode?: string;11}1213async function findOrder(id: string): Promise<Order | undefined> {14  const res = await fetch(`/api/orders/${id}`);15  if (res.status === 404) return undefined;16  return (await res.json()) as Order;17}
  1. Line 7 The table of contents: an order has an id, a list of lines, and maybe a coupon code. No function read yet.
  2. Line 10 The ? says the coupon may be missing. Every use of it must cope with that.
  3. Line 13 The signature: it is async, and the answer may be undefined. So callers must await and check.
  4. Line 16 A cast. Nothing checks that the server's JSON really has this shape: as just tells the checker to trust it.

Take away

  • Read signatures and field lists first: they say what goes in, what comes out, and what can be missing.
  • | undefined, | None and ? mean "handle the missing case".
  • Types are a claim: ask what checks them when data comes from outside, or goes through a cast.

Quiz: test yourself

7 questions: a quick quiz, then a review drill. Pick an answer to see why it's right.