Sub topic 19
Compile-time versus runtime privacy
This chapter assumes you know the private and protected modifiers, have read the previous chapter on ECMAScript #private fields, and can read basic tsconfig.json options. It explains where each kind of privacy is enforced, what that means for the code you ship, and how to choose between them.
Two enforcement points
A TypeScript program passes through two stages. The type checker (tsc) analyzes your source and reports errors. After that, the emitted JavaScript runs in Node.js or a browser, and the type checker is gone.
- The
privateandprotectedkeywords are enforced only in the first stage. - A
#namefield is enforced in both stages. The checker rejects outside access, and the JavaScript engine rejects it too.
What the `private` keyword leaves behind
The compiler removes the modifier and emits an ordinary property. This example shows the consequences.
class Session {
private token: string;
#secret: string;
constructor(token: string, secret: string) {
this.token = token;
this.#secret = secret;
}
static hasSecret(value: unknown): boolean {
return typeof value === "object" && value !== null && #secret in value;
}
}
const session = new Session("t-123", "s-456");
// Type-level escape hatches for `private`
console.log((session as any).token); // t-123
console.log(session["token"]); // t-123: bracket notation is allowed by design
// Runtime visibility
console.log(Object.keys(session)); // ["token"]
console.log(JSON.stringify(session)); // {"token":"t-123"}
console.log(Session.hasSecret(session)); // true
console.log(Session.hasSecret({})); // falseSeveral things follow from this output:
session["token"]compiles without error. TypeScript deliberately lets bracket access skip theprivatecheck, so you can reach into a class in tests or debugging.Object.keysandJSON.stringifyseetoken. If you serialize an object that holds a password or API key in aprivatefield, the value ends up in the JSON output.- The
#secretfield appears in neither. It is stored in an internal slot, not as a normal property. - The expression
#secret in valueis a brand check. It tells you whether an object was constructed by this class, whichinstanceofcannot guarantee when prototypes are manipulated. It needs TypeScript 4.5 or later.
The following lines fail, and the second fails in any engine, even if you cast to any:
// session.token; // Error at compile time: 'token' is private
// (session as any).#secret; // SyntaxError: private names must be declared in an enclosing classWhat the compiler emits
The target in tsconfig.json changes how #private fields are compiled.
| Target | Output for `#secret` | Consequence |
|---|---|---|
| ES2022 or later | Native `#secret` syntax | Engine enforces privacy directly |
| ES2015 to ES2021 | A `WeakMap` per field, accessed through helper functions | Privacy preserved, with some runtime overhead and larger output |
| ES5 or lower | Not supported | Compile error |
The private keyword has no effect on emitted code at any target. It costs nothing at runtime, and it protects nothing at runtime.
Behavioral differences
Privacy differs in more than visibility. Check these before choosing.
- Subclass name clashes. A subclass cannot declare a member with the same name as a base class
privatemember, because the checker treats them as the same slot.#namesare scoped to the declaring class, so a base class and a subclass can each have their own#idwithout conflict. - No
protectedequivalent. A#fieldis invisible to subclasses. If a subclass needs the data, expose it through aprotectedmethod or accessor. - Same-class access. Within a class body, both kinds allow access to another instance's private members, for example
other.balanceorother.#balanceinside a method of the same class. - Reflection and tooling. Debuggers and some serialization libraries can see
privateproperties. They cannot see#privatefields from ordinary code. - Parameter properties. The shorthand
constructor(private x: number)always creates a TypeScript-private property. There is no#form of it. For a#field you write the declaration and the assignment yourself. - Testing. Tests can reach
privatemembers with(obj as any).xorobj["x"].#privatemembers cannot be reached from a test, so you must test through the public API. - Mocks and proxies. Calling a method that uses
#xon aProxythrows aTypeError, because the proxy does not hold the private slot.privatemembers have no such problem.
The proxy gotcha surprises people most often:
class Box {
#value = 42;
read(): number {
return this.#value;
}
}
const proxy = new Proxy(new Box(), {});
try {
proxy.read();
} catch (error) {
console.log((error as Error).constructor.name); // TypeError
}The method runs with this set to the proxy, and the proxy has no #value slot, so the engine throws.
Choosing between them
Use these criteria in order:
- Is it a security boundary? Neither keyword is a sandbox, but only
#privateholds against code you do not control, such as a third-party script on the page. Even so, treat secrets as a design problem. Keep them out of objects that get logged or serialized. - Do subclasses need access? If yes, use
protected. If no, either works. - Do you need to serialize or inspect the object? If you want
JSON.stringifyto leave the field out,#privatedoes that automatically. Withprivateyou must write atoJSONmethod. - Do your tools and target support it? For ES2015 to ES2021 targets, check the size and speed cost of the
WeakMaphelpers. Check that your test and mocking tools cope with#fields. - Is the codebase consistent already? Mixing both styles in one class is legal but confusing. Pick one per project, and write the choice in your style guide.
A reasonable default is private for internal structure that a team agrees not to touch, and #private for state whose integrity a class must guarantee, such as invariants and handles.
Summary of the model
The checker applies private and protected rules to your source and then discards them. #private is a JavaScript feature that TypeScript also type-checks, so it survives compilation and the engine enforces it. Choose by asking who must be prevented from reaching the data: teammates reading the source, or any code running in the same process.
Exercise
A class has private apiKey: string. A colleague calls JSON.stringify(client) in a logging statement. Does the key appear in the log, and what single change to the field declaration would stop it without adding a toJSON method?
Show answer
Yes, the key appears. The private keyword is erased at compile time, so apiKey is an ordinary own property that JSON.stringify serializes. Changing the declaration to #apiKey: string stores it in an engine-enforced private slot, which JSON.stringify and Object.keys do not see. Remember that subclasses can no longer access it directly.
Exercise
You write const proxy = new Proxy(new Box(), {}); proxy.read(); where read() returns this.#value. What happens, and why does the same pattern work if #value is replaced by private value?
Show answer
It throws a TypeError. When called through the proxy, this is the proxy object, and the proxy has no #value private slot, so the engine rejects the access. A private value field is an ordinary property, and the proxy forwards the property lookup to the target, so it works.