TypeScript theorytheory 0/50 · 0%
Types · easy

4. Object types & interfaces

Describing the shape of objects.

An `interface` (or an inline object type) describes the properties an object must have, including their types.

ts
interface Wallet {
  address: string;
  balance: number;
  label?: string; // optional
}

function show(w: Wallet): string {
  return `${w.address}: ${w.balance}`;
}

Properties marked with `?` are optional. `readonly` prevents reassignment after creation. Structural typing means any object with the right shape satisfies the interface — there's no need to explicitly "implement" it.

ts
interface Point { readonly x: number; readonly y: number; }
const p: Point = { x: 1, y: 2 };
p.x = 5; // error: readonly

Check your understanding

  1. 1. What does a `?` after a property name mean in an interface?

  2. 2. TypeScript uses which kind of typing for objects?

  3. 3. What does `readonly` do to a property?