TypeScript Developer interview question · Most asked

What is structural typing in TypeScript?

Summary

TypeScript checks compatibility by shape (structure), not by declared names: a value is assignable to a type if it has all the required members with compatible types, regardless of which class or interface created it.

Longer Answer

This differs from nominal typing in Java or C#. Two unrelated interfaces with the same members are interchangeable. Excess property checks only apply to fresh object literals. When you need nominal-like behavior (e.g., not mixing UserId and OrderId strings), use branded types.

Code Example

interface Point { x: number; y: number }
class Vector { constructor(public x: number, public y: number) {} }

const p: Point = new Vector(1, 2); // OK: same shape

type UserId = string & { readonly __brand: "UserId" };
type OrderId = string & { readonly __brand: "OrderId" };
declare function getUser(id: UserId): void;
// getUser("abc" as OrderId); // Error: brands differ

Key Points

  • Compatibility by shape
  • Unrelated types with same shape are interchangeable
  • Excess property checks on object literals
  • Brands simulate nominal typing

More most-asked TypeScript Developer questions

← All TypeScript Developer questions