How do access modifiers interact with structural typing when checking class compatibility?
Short answer
Structural typing normally only cares about shape, but private and protected members break this: two classes with identically-named private/protected members are still considered incompatible UNLESS one is literally derived from the other, because TypeScript tracks the declaring…
Advertisement
AModel answer
Structural typing normally only cares about shape, but private and protected members break this: two classes with identically-named private/protected members are still considered incompatible UNLESS one is literally derived from the other, because TypeScript tracks the declaring class as part of each private/protected member's identity.
class A { private secret = 1; }
class B { private secret = 1; }
let a: A = new B(); // Error: Property 'secret' is private in type 'B' but not related to A's 'secret'Real-world example
Understanding a confusing compiler error where two seemingly identical classes aren't assignable to each other.
Likely follow-ups
- Does this same restriction apply to 'public' members?
Related topics