Structural Typing
PronunciationSTRUK-cher-ul TY-ping
Definition
Structural typing decides whether an object fits a type by the methods and fields it has, not by the class it inherits from. In Python this is a Protocol.
Where you hear it
In TypeScript, in Python typing discussions, and when designing code that should accept any object with the right methods.
Examples
Any class with a
due()method satisfies the protocol, even if it never mentions it.TypeScript types are structural, so matching shapes are interchangeable.
The function accepts anything with a due() method, so the new invoice class works without inheriting anything.
Common mistake
Confusing it with inheritance. With structural typing a class does not need to extend anything to qualify.
Don't confuse with
Nominal typing, where a class must declare that it implements an interface. Java works this way.
Say it at work
- In a meeting or chat
Define a protocol instead of forcing everyone to inherit from a base class.
- In an email or ticket
It's structural: anything with these two methods works.
Keep exploring
More in Programming Fundamentals