$ node dog.jsRex 3tsctype checker!✓1type ID = number | string;2interface Pet { name: string }3interface Pet { age: number }4interface Dog extends Pet { id: ID }5const d: Dog = { name: "Rex", id: 7 };const d: Dog = { name: "Rex", age: 3, id: 7 };6console.log(d.name, d.age);nameageidstringnumberIDnumber | stringname: stringage: number+ id: IDstringnumberIDTSJS
Front: dog.ts (an alias and interfaces). Back right: tsc, the type checkerThe shape tsc builds: one cell per property. Back left: the laptop that runs the JavaScriptTiles: parts of the shape going into tsc, and each property's type coming back outdog.ts names types two ways: a type alias (line 1) and interfaces (lines 2 to 4). tsc, the type checker, is at the back right; in front of it, the shape it builds for Pet and then Dog (name, age, id). Only the alias can name the union number | string. Only the interface can be declared again and merge: line 3 adds age to Pet. extends (or & for an alias) builds Dog. tsc then catches line 5's missing age. After the fix, lines 1 to 4 are erased and the program prints Rex 3.

Two ways to name a type

  1. TypeScript lets you name a type in two ways. type makes a type alias; interface declares an object shape. For plain objects they do the same job. This file uses both, and shows where they differ.

Building a shape

Bugs caught

Run it

What happens

;; step 1/8 · why
dog.ts  (TypeScript)
> 1  type ID = number | string;
> 2  interface Pet { name: string }
  3  interface Pet { age: number }
  4  interface Dog extends Pet { id: ID }
  5  const d: Dog = { name: "Rex", id: 7 };
  6  console.log(d.name, d.age);

type ID = ...        a type alias: a new name for a type
interface Pet {...}  an interface: a named object shape

The TypeScript Handbook suggests using interface until you need something only an alias can do, such as naming a union. Either works for plain object shapes. The dog.js shown is what tsc 5.9 writes with --target es2022. With no settings tsc 5.9 targets old JavaScript (ES5) and writes var instead of const; the types are removed either way.