Skip to content

Structural typing allows unexpected assignment

Quick summary

An object with extra properties was assigned to a type with fewer properties — structural typing allows it, but it may hide a bug.

Why this happens

  • An object literal with extra properties is passed to a function expecting a type with fewer properties

  • Two types with the same shape but different semantic meaning are interchangeable due to structural typing

  • A type was widened through structural assignment, losing type safety on the extra properties

Minimal example

✗ Broken code
interface User { id: number; name: string; }
interface Product { id: number; name: string; }
const user: User = { id: 1, name: 'Alice' };
const product: Product = user; // allowed! structurally identical
product.id = 999; // mutates user.id too!
✓ Fixed code
type UserId = number & { __brand: 'UserId' };
interface User { id: UserId; name: string; }
interface Product { id: number; name: string; }
const user: User = { id: 1 as UserId, name: 'Alice' };
// const product: Product = user; // error: UserId is not assignable to number

Branding the UserId type with a phantom property prevents it from being assigned to a plain number, avoiding the structural typing pitfall.

How to diagnose

  • Check if the object has properties beyond what the target type requires — they are allowed but may be unintended

  • Use a branded type or nominal typing pattern to prevent semantically different types from being interchangeable

  • Compare the source and target types to understand what extra properties are being silently carried

How to fix

  • Use a branded type (type UserId = string & { __brand: 'UserId' }) to prevent cross-type assignment

  • Add excess property checks by using object literals directly (which trigger excess property checks) instead of variables

  • Explicitly pick only the needed properties: const { a, b } = source; target = { a, b }

How to prevent

  • Use branded types for semantically distinct types that happen to have the same structure

  • Be aware that TypeScript uses structural typing — extra properties are allowed in assignments from variables

Related Resources

Related Glossary

Related Lessons

← Back to language