How does structural typing handle two interfaces that are 'shape-identical' but declared completely independently?
Short answer
Since compatibility is purely shape-based, two independently-declared interfaces (or a class and an interface, or two unrelated classes) with IDENTICAL public shapes are considered fully interchangeable everywhere — TypeScript doesn't care that they have different names or were…
Advertisement
AModel answer
Since compatibility is purely shape-based, two independently-declared interfaces (or a class and an interface, or two unrelated classes) with IDENTICAL public shapes are considered fully interchangeable everywhere — TypeScript doesn't care that they have different names or were never explicitly related.
interface Named { name: string; }
interface Labeled { name: string; }
function greet(entity: Named) { console.log(entity.name); }
const item: Labeled = { name: 'Widget' };
greet(item); // works fine, despite 'Labeled' having no declared relationship to 'Named'Real-world example
Passing values between two independently-designed modules or libraries that happen to use identically-shaped but differently-named types.
Likely follow-ups
- Does this same interchangeability apply if the two types have PRIVATE members with the same names, as covered in the Classes topic?
Related topics