EasyType System📖 Theory Question

What is structural typing (duck typing) in TypeScript?

💡

Hint

Compatibility is based on shape, not name — if it has the right properties, it is the right type

Full Answer

TypeScript uses structural typing: two types are compatible if they share the same shape (property names and types), regardless of their declared names. This is unlike nominal typing systems (Java, C#) where the type name matters.

interface Point {
  x: number;
  y: number;
}

// An object literal with the right shape is assignable
const p: Point = { x: 1, y: 2 }; // ✅

// A class with the right shape is also assignable
class Vector {
  constructor(public x: number, public y: number) {}
}
const v: Point = new Vector(3, 4); // ✅ — Vector is structurally compatible

// Extra properties are fine when assigning to a less specific type
const extended = { x: 1, y: 2, label: 'origin' };
const p2: Point = extended; // ✅ — subset assignment (not a fresh literal)

// ❌ Fresh object literals trigger excess property checks
const p3: Point = { x: 1, y: 2, label: 'origin' }; // Error: 'label' not in Point

Practical implications:

  • Functions accepting a type will accept any superset — enables flexible APIs
  • You don't need implements to satisfy an interface — the shape is enough
  • Excess property checks only apply to fresh object literals
function printPoint(p: Point) { console.log(p.x, p.y); }

// All of these work — all have x and y:
printPoint({ x: 1, y: 2 });
printPoint(new Vector(1, 2));
printPoint({ x: 1, y: 2, z: 3 }); // extra props OK in this context
💡 Structural typing is why TypeScript feels flexible. You can define interfaces after the fact to describe shapes that already exist — great for working with third-party code.

More Type System Questions

EasyWhat is type inference in TypeScript and when does it kick in?→EasyWhat is the difference between any, unknown, and never in TypeScript?→EasyWhat are type assertions and when should you use them?→EasyWhat are union types and intersection types? When do you use each?→

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint