Course outline · 0% complete

0/26 lessons0%

Course overview →

Typed Objects

lesson 2-2 · ~11 min · 5/26

Describing an object's shape

Almost everything a real program passes around is an object: a user record, a product, a config. That makes object shapes the place where typos and missing fields do the most damage — and the place where the type system pays off most. Objects get a type that lists each property and its type:

const user: { name: string; age: number } = {
  name: "Ada",
  age: 36,
};

The part in braces after the colon is the object type: property names with their types. TypeScript now enforces the shape in both directions:

  • Missing a property? Property 'age' is missing at compile time
  • Adding an extra one? Error, the shape says exactly name and age
  • Typo like user.nmae? Error, with a helpful Did you mean 'name'?

That last one matters. In JavaScript, user.nmae silently gives undefined and the crash happens somewhere else entirely. You debugged exactly that class of bug in Advanced JavaScript.

Code exercise · typescript

Run it, then change user.name to user.nmae in the first console.log and run again to see the typo caught.

Code exercise · typescript

Objects rarely travel alone. An array of typed objects is the most common data shape in real code, and the annotation composes exactly as you would guess: { name: string; hours: number }[] reads as "array of objects with this shape". Run it, then add { name: "Alan" } to the array and run again to see the missing property caught.

Quiz

Given const p: { x: number; y: number } = ..., what happens at compile time if you write p.z = 5?

Code exercise · typescript

Your turn. Create book with the shape { title: string; pages: number; inPrint: boolean } holding "Dune", 412, true. Print the two lines shown in the expected output.