Why does TypeScript's structural typing allow assigning a class instance to an interface even when the class has EXTRA methods beyond what the interface requires?
Short answer
Structural typing (outside the specific excess-property-check-on-literals case) is fundamentally about the target type's requirements being a SUBSET of what the source provides — having additional, unused capabilities is always safe from the consumer's perspective, since nothing…
Advertisement
AModel answer
Structural typing (outside the specific excess-property-check-on-literals case) is fundamentally about the target type's requirements being a SUBSET of what the source provides — having additional, unused capabilities is always safe from the consumer's perspective, since nothing requires those extra members to be used or even acknowledged.
interface Greetable { greet(): void; }
class Person {
greet() { console.log('Hi'); }
walk() { console.log('Walking'); } // extra method, not required by Greetable
}
const g: Greetable = new Person(); // OK -- Person satisfies AND exceeds Greetable's shapeReal-world example
Passing a fully-featured class instance to a function that only cares about (and only interacts with) a small subset of its capabilities.
Likely follow-ups
- How does this relate to the Interface Segregation Principle from object-oriented design?
Related topics