Lesson 1.1Free preview

Structural typing and assignability

TypeScript compares types by structure.

12mIntermediate24.7k students

Overview

Shape, not name

TypeScript compares types by structure. Two separately declared types with the same members are interchangeable, and a value is assignable anywhere its shape satisfies the target — the name it was declared under is irrelevant.

The exception is excess property checking on object literals assigned directly to a typed target, which catches typos in configuration objects. Assign through a variable first and the check does not apply, which surprises people regularly.

When two structurally identical types must not mix — a user id and an order id, both strings — add a phantom property to brand them. The compiler then treats them as distinct even though the runtime value is unchanged.

In this lesson you will:

  • Understand why shape matters more than name
  • Predict when an extra property is allowed
  • Use branded types when structure is not enough

Resources

Next Lesson
Structural typing and assignability — TypeScript Deep Dive — Vertex