What it is and why to use it
A field whose name begins with # has JavaScript runtime private-field semantics. This differs from TypeScript’s private modifier, which primarily constrains access during type checking. Runtime private fields are useful for implementation state that should not be accessed through ordinary property names.
Common mistakes and limitations
Private fields are not a general place to store secrets from the user running the application. Subclasses cannot directly access a base class’s #field. Target and runtime support still matter; TypeScript can transform supported features for some older targets.
Run this example
Use TypeScript 5.8 or later with strict checking and an ES2022 target. Save each complete example independently as example.ts, compile it, then run the generated JavaScript with a compatible Node.js installation. Compiler-only options below affect checking; they do not add runtime validation.
Terminal — compile and run
npx tsc example.ts --strict --target ES2022 --module commonjs
node example.jsSyntax
#count = 0;Examples
ECMAScript #private Fields versus private
Standalone TypeScript 5.8+ example; expected output is explained below.
class Counter {
#count = 0;
increment(): number { return ++this.#count; }
}
const counter = new Counter();
console.log(counter.increment());
console.log(Object.keys(counter).length);- increment accesses the private field within its declaring class.
- The first increment returns 1.
- Object.keys finds no public enumerable field for #count because it is not an ordinary string-key property. The ES2022 target preserves native private-field syntax.
- Expected output: 1 0
Best practices
- Private fields are not a general place to store secrets from the user running the application. Subclasses cannot directly access a base class’s #field. Target and runtime support still matter; TypeScript can transform supported features for some older targets.
- Keep external-input validation separate from compile-time type descriptions.
Runtime & versions
Compiled to JavaScript. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
TypeScript Handbook