typestar

type against interface in TypeScript

Interfaces merge and are implemented; type aliases compose.

interface Tour {
  slug: string;
}

interface Tour {
  steps: number; // declaration merging: one Tour with both
}

interface Encore extends Tour {
  script: string;
}

type Base = { slug: string };
type WithSteps = Base & { steps: number };
type Either = Base | { legacy: true };

const tour: Tour = { slug: "basics", steps: 26 };
const encore: Encore = { ...tour, script: "lines.ts" };
const merged: WithSteps = tour;
const either: Either = { legacy: true };

console.log(tour.steps, encore.script, merged.slug, "legacy" in either);

How it works

  1. Two interfaces of the same name merge into one.
  2. Only a type alias can name a union or a mapped type.
  3. extends on an interface, & on an alias.

Keywords and builtins used here

The run, in numbers

Lines
22
Characters to type
528
Tokens
126
Three-star pace
95 tpm

At the three-star pace of 95 tokens a minute, this run takes about 80 seconds.

Type this snippet

Step 3 of 5 in Objects & interfaces, step 13 of 23 in Types & annotations.

← Previous Next →