Ch 3 · Describing Your Data Once · TypeScript

Topic 3 of 6 in TypeScript — Types That Protect Paid Work — 4 lessons.

interface: One Shape, Reused Everywhere

Every real project has three or four shapes of data that travel everywhere: a client, an order, a user, a line item. Writing that shape inline every time is how the definitions drift apart. An interface gives the shape a name, in one place, and every function that touches it refers to the name.

type vs interface

You will see both interface Client { ... } and type Client = { ... } in real codebases, and both work for describing an object. The genuine difference that matters at this stage is what else each can do.

Optional and readonly

A question mark after a property name makes it optional: the object may have it or may not. A readonly prefix means the property can be set when the object is created and never reassigned afterwards. Both are about writing down what is actually true, so the compiler can hold you to it.

Check Yourself

All topics in TypeScript Beginner

  1. Why TypeScript Is Worth Your Time
  2. The Types You Will Use Every Day
  3. Describing Your Data Once
  4. Functions That State Their Terms
  5. The Holes in the Fence
  6. The Project You Set Up On Every Job