Access modifiers and private fields
Concept and syntax
public permits access from outside; protected permits access from the class and subclasses; TypeScript private restricts checked access to the declaring class. ECMAScript #private fields additionally enforce privacy at runtime. TypeScript private is not equivalent to #private. Choose based on the required runtime boundary.
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 Vault {private label="tea";#count=7;read(){return this.label+":"+this.#count;}}const vault=new Vault();console.log(vault.read(),Object.keys(vault).join(","));Expected output:
tea:7 labelCommon mistake
Intentionally invalid; compile separately and do not execute.
class Vault {private count=7;}const vault=new Vault();console.log(vault.count);Expected diagnostic: TS2341. The private field is inaccessible through ordinary checked property access. Expose a public method if intended.
Practice and recap
Compare Object.keys for public, TypeScript private and #private fields.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Access modifiers and private fields — 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 Vault {private label="tea";#count=7;read(){return this.label+":"+this.#count;}}const vault=new Vault();console.log(vault.read(),Object.keys(vault).join(","));Which diagnostic and explanation match the rejected example under the lesson settings?
class Vault {private count=7;}const vault=new Vault();console.log(vault.count);