Sikau

TypeScript · Day 6 · about 25 min

Object types

type aliases and interfaces.

Describe your data

Most data is objects: users, products, orders. Give their shape a name once, and TypeScript checks every place they're created, read or passed around — and your editor autocompletes their properties.

type and interface

type Dish = {
  name: string;
  price: number;
  veg?: boolean;
  readonly id: number;
};

const momo: Dish = { id: 1, name: "Momo", price: 180 };
momo.price = 200;
momo.id = 2;

interface Customer {
  name: string;
  favourites: Dish[];
}
const sita: Customer = { name: "Sita", favourites: [momo], phone: "98…" };

type and interface are almost interchangeable for objects. A common rule: use interface for object shapes and type for everything else (unions, functions, tuples).

The rest of this lesson

  • Extra property checksexplain
  • Structural typingexplain
  • Is it valid?predict
  • Shape, not namepredict
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 24 lessons of TypeScript