Type Compatibility | Typescript
Introduction#
Type compatibility in TypeScript is based on structural subtyping. Structural typing is a way of relating types based solely on their members. This is in contrast with nominal typing.
In nominally-typed languages like C# or Java, the equivalent code would be an error because the Person class does not explicitly describe itself as being an implementer of the Named interface.
Starting out#
The basic rule for TypeScript's structural type system is that x is compatible with y if y has at least the same members as x.
Comparing two functions#
Enums#
Classes#
When comparing two objects of a class type, only members of the instance are compared
Private and protected members in classes#
Private and protected members in a class affect their compatibility. When an instance of a class is checked for compatibility, if the target type contains a private member, then the source type must also contain a private member that originated from the same class. Likewise, the same applies for an instance with a protected member. This allows a class to be assignment compatible with its super class, but not with classes from a different inheritance hierarchy which otherwise have the same shape.