Structural typing
Definition:
In order to determine if two types are assignable, the compiler exhaustively compares all their properties.
This contrasts with nominal typing, which works like:
Two types only are assignable if they were created from the same constructor OR from an explicitly related constructor. (explicitly related usually means: extends or implements).
Given two classes A and B:
Now let a function require A as input.
The function accepted B as input since its properties were considered assignable;
This would not be allowed on nominal typing, since it would require
B
to explicitlyextend
orimplement
A
;Since we are just comparing properties, just directly passing a conforming object also works;
The last line errors because TS applies a special rule which enforces exact properties if the argument is a literal;
Last updated