Want a faster signal before interviews? Take the Interview Ready Check →

DAY 10 OF 30

Structural typing

Yesterday, in one sentence

What is declaration merging in TypeScript?

Interview question

What is the difference between an interface and a type alias?

TypeScript decides whether two types are compatible by comparing their shape, not their name. This is called structural typing, and it is sometimes called duck typing: if it looks like a duck, it is a duck.

interface Mutant {
  id: number;
  power: string;
}

type Magic = {
  id: number;
  power: string;
};

const juggernaut: Magic = { id: 1, power: "unstoppable" };

const mutant: Mutant = juggernaut; // ok, the shapes match

Mutant was declared as an interfaceInterface and Magic as a type aliasType Alias, but they have the same properties with the same types, so a value of one is assignable to the other.

Check yourself

How does TypeScript treat these two types?
interface Peter {
  name: string
  city: string
}

type Miles = {
  name: string
  city: string
}
What is structural typing (duck typing) in TypeScript?