Sub topic 18
ECMAScript #private fields
This chapter assumes you know TypeScript's private keyword, class fields and constructors, and how this behaves in JavaScript methods. It covers the #name syntax, which JavaScript itself enforces at runtime, and the cases where it behaves differently from private.
What a #private field is
A #private field is part of the JavaScript language (ECMAScript 2022). Any identifier that starts with # is a private name. Only code written inside the class body can read or write it. TypeScript supports the syntax and also checks it at compile time. Unlike the private keyword, the runtime enforces it. The restriction survives compilation and type assertions.
class Counter {
private tsCount = 0;
#realCount = 0;
increment(): void {
this.tsCount++;
this.#realCount++;
}
get value(): number {
return this.#realCount;
}
}
const counter = new Counter();
counter.increment();
console.log((counter as any).tsCount); // 1: the TypeScript private is not enforced at runtime
console.log(Object.keys(counter)); // ["tsCount"]: the #realCount field is not exposed
console.log(counter.value); // 1The commented-out line (counter as any).#realCount is a syntax error. The parser rejects any #name reference outside the class body that declares it. No cast can get around that.
Declaring and using #private members
The # is part of the name. #count and count are two different members, and both can exist in one class. You always access the field with this.#count, never this["#count"], because the latter is an ordinary string key.
You can declare private fields, methods, accessors, and static members:
class Session {
static #created = 0;
#token: string;
#expiresAt: number;
constructor(token: string, ttlMs: number) {
this.#token = token;
this.#expiresAt = Date.now() + ttlMs;
Session.#created++;
}
static get created(): number {
return Session.#created;
}
#isExpired(): boolean {
return Date.now() > this.#expiresAt;
}
get tokenIfValid(): string | undefined {
return this.#isExpired() ? undefined : this.#token;
}
}
const s = new Session("abc123", 60_000);
console.log(s.tokenIfValid); // abc123
console.log(Session.created); // 1Rules to remember:
- A
#member cannot takepublic,private, orprotected. The#already says "private". - A
#member can havereadonly, as inreadonly #id = 1. - Parameter properties do not work with
#. You cannot writeconstructor(#x: number). Declare the field and assign it in the body. - Each
#namemust be declared once per class. Declaring it twice is an error.
How it works at runtime
A #private field is not a property. It does not appear in Object.keys, JSON.stringify, for...in, or Object.getOwnPropertyNames. Reflection cannot see it. Each class definition owns its own private names, much as a closure owns its variables.
For that reason, a #private field never conflicts with a field of the same name in a subclass:
class Base {
#secret = "base";
readSecret(): string {
return this.#secret;
}
}
class Derived extends Base {
#secret = "derived";
readDerivedSecret(): string {
return this.#secret;
}
}
const d = new Derived();
console.log(d.readSecret()); // base
console.log(d.readDerivedSecret()); // derivedBoth fields exist on one object, and each class reads its own. With TypeScript's private, declaring the same name in both classes is a compile error.
Brand checks with `in`
Reading #x from an object that lacks it throws a TypeError at runtime. You can test for it first with the in operator. This works inside the class:
class Token {
#value: string;
constructor(value: string) {
this.#value = value;
}
static isToken(candidate: unknown): candidate is Token {
return typeof candidate === "object" && candidate !== null && #value in candidate;
}
}
console.log(Token.isToken(new Token("x"))); // true
console.log(Token.isToken({ value: "x" })); // false#value in candidate is true only for objects that were constructed by this class. It is a reliable runtime type check that no plain object can fake.
Differences from TypeScript `private`
| Aspect | `private` keyword | `#private` field |
|---|---|---|
| Enforced by | TypeScript compiler only | JavaScript runtime |
| Present after compilation | No, it becomes an ordinary property | Yes, if the target supports it |
| Bypass with `as any` or `obj["x"]` | Possible | Not possible |
| Visible to `Object.keys` and `JSON.stringify` | Yes | No |
| Same name in a subclass | Compile error | Allowed, separate fields |
| Usable in parameter properties | Yes | No |
| Accessible from another instance of the same class | Yes | Yes |
Both forms allow access to another instance of the same class. Inside a class, other.#value works when other is of the same class. Neither form is per-instance private.
Gotchas
Compile target
The # syntax requires target ES2015 or later. Below ES2022, TypeScript rewrites #name into a WeakMap (one per field) and helper functions. The code still works, but it is slower than native fields and produces larger output. With target: ES2022 or newer, it emits native #name syntax.
Debugging and serialization
Because private fields are not properties, console.log in some environments shows them and in others does not. JSON.stringify never includes them. If an object must serialize its state, add an explicit toJSON() method.
class User {
#email: string;
constructor(email: string) {
this.#email = email;
}
toJSON(): { email: string } {
return { email: this.#email };
}
}
console.log(JSON.stringify(new User("[email protected]"))); // {"email":"[email protected]"}Proxies and `this`
A Proxy around a class instance does not forward private access. Calling a method that uses this.#x through a proxy fails with a TypeError, because the proxy object does not have the private field. Calling Reflect.get with a different receiver has the same effect. The same failure occurs when you detach a method and call it with the wrong this.
No `protected` equivalent
There is no #protected. Subclasses cannot read a #field of their parent. If a subclass needs access, expose it through a protected method or accessor on the parent, or keep the field as TypeScript protected.
Type compatibility
Classes with #private members are compared nominally, like those with private. Two classes with identical shapes are not assignable to each other if either has a # member declared separately.
Choosing between them
Use #private when the data is sensitive or when other code may be untyped JavaScript, so a compile-time check would not protect it. Use it in library code, where consumers might use any. Use private when you need parameter properties, a faster non-WeakMap output on old targets, easy inspection in a debugger, or tests that deliberately reach into internals. Pick one style per codebase, so readers know which guarantee they are getting.
Exercise
A class declares private id = 1 and another declares #id = 1. You call JSON.stringify on an instance of each. What does each output contain, and which one can (obj as any).id read?
Show answer
The instance with private id serializes as {"id":1}, and (obj as any).id returns 1 because the field is an ordinary property at runtime. The instance with #id serializes as {}, and (obj as any).id returns undefined, because #id is not a property and no cast can reach it.
Exercise
Write a static method isAccount(x: unknown): x is Account for a class that has a field #balance, without using instanceof.
Show answer
static isAccount(x: unknown): x is Account { return typeof x === "object" && x !== null && #balance in x; }. The in check on a private name is true only for objects created by that class's constructor.