Private and protected origins
Concept and syntax
Private and protected members introduce a nominal-like restriction into structural class compatibility: compatible nonpublic members must originate from the same declaration hierarchy. A derived class inherits the relevant origin; unrelated classes with equally named private fields are incompatible.
Working example
Save each snippet separately as main.ts in a fresh directory. Compile with tsc --strict --target ES2022 --module commonjs --moduleDetection force --skipLibCheck --noEmitOnError main.ts, then run the accepted example with node main.js. Forced module detection isolates snippet names from global declarations.
class Base {private id=7; read(){return this.id;}}class Child extends Base {}const item:Base=new Child();console.log(item.read());Expected output:
7Common mistake
Intentionally invalid; compile separately and do not execute.
class A {private id=1;}class B {private id=1;}const item:A=new B();Expected diagnostic: TS2322. The private declarations have different origins. Use a shared base or a public structural interface.
Practice and recap
Repeat with protected members and a common superclass.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Private and protected origins — knowledge check
Check the contract, trace output, and diagnose an invalid example.
Which statement about this lesson’s concept is accurate?
What is the complete stdout, represented as a JSON string (including newline characters)?
class Base {private id=7; read(){return this.id;}}class Child extends Base {}const item:Base=new Child();console.log(item.read());Which diagnostic and explanation match the rejected example under the lesson settings?
class A {private id=1;}class B {private id=1;}const item:A=new B();