Sub topic 8
private: hiding implementation details
This chapter assumes you know basic TypeScript types, how classes declare fields and constructors, and how this works in JavaScript. It covers what private guarantees, what it does not guarantee, and how to use it to protect the rules your class depends on.
What private does
A member marked private can be used only inside the body of the class that declares it. That includes fields and methods. Code outside the class cannot read, write, or call the member, and the compiler reports an error if it tries.
class Account {
private balance: number;
constructor(initialBalance: number) {
this.balance = initialBalance;
}
deposit(amount: number): void {
this.assertPositive(amount);
this.balance += amount;
}
getBalance(): number {
return this.balance;
}
private assertPositive(amount: number): void {
if (amount <= 0) {
throw new Error("Amount must be positive");
}
}
}
const account = new Account(100);
account.deposit(50);
console.log(account.getBalance()); // 150
// account.balance = 0; // Error: Property 'balance' is private and only accessible within class 'Account'.
// account.assertPositive(5); // Error: Property 'assertPositive' is private and only accessible within class 'Account'.The class has two kinds of members. The public ones (deposit, getBalance) form its API. The private ones (balance, assertPositive) are the implementation. Because outside code cannot touch balance, every change to it goes through deposit, so the positive-amount rule is always enforced.
Why hide members
Hiding members gives you two benefits.
- Invariants. An invariant is a condition that must always hold, such as "the balance is never changed by a non-positive deposit". Private fields let one place in your code enforce it.
- Freedom to change. Callers cannot depend on what they cannot see. You can later store the balance in cents, cache it, or load it lazily without breaking any caller.
A good default is to make every field private and widen access only when a caller needs it.
Access rules in detail
The rule is based on where the code is written, not on which object it runs against. Two consequences follow.
Other instances of the same class
Inside a class, you can read the private members of any instance of that class, not only this. This is useful for comparison methods.
class Money {
private cents: number;
constructor(cents: number) {
this.cents = cents;
}
equals(other: Money): boolean {
return this.cents === other.cents; // allowed: same class body
}
}
console.log(new Money(500).equals(new Money(500))); // trueSubclasses
A subclass is a different class body, so it cannot use the parent's private members. Use protected for that, which a later chapter covers.
class Base {
private secret = 1;
}
class Derived extends Base {
reveal(): number {
// return this.secret; // Error: Property 'secret' is private and only accessible within class 'Base'.
return 0;
}
}
// A subclass also cannot redeclare a private name from its parent:
// class Clash extends Base { private secret = 2; }
// Error: Class 'Clash' incorrectly extends base class 'Base'.
// Types have separate declarations of a private property 'secret'.The second error surprises many people. A private name in a parent still occupies that name in the child's type, even though the child cannot use it. Pick distinct names, or make the member protected if the child should work with it.
| Code location | Reads a `public` member | Reads a `private` member |
|---|---|---|
| Inside the declaring class | Yes | Yes, on any instance of the class |
| Inside a subclass | Yes | No |
| Outside the class | Yes | No |
Common errors and gotchas
private is erased at runtime
private is a compile-time check only. The compiled JavaScript has ordinary properties with no protection. Two escape hatches show this.
const acct = new Account(100);
console.log(acct["balance"]); // 100: bracket notation with a string literal skips the check
console.log((acct as any).balance); // 100: `any` disables the checkTreat private as a way to stop honest mistakes by other developers. It does not stop deliberate access, and it is not a security boundary. The chapter on #private fields covers the JavaScript feature that is enforced at runtime.
Private fields still serialize
Because the fields exist at runtime, tools that walk an object's properties will see them. JSON.stringify is the common case.
class User {
constructor(public name: string, private password: string) {}
}
console.log(JSON.stringify(new User("ann", "pw1")));
// {"name":"ann","password":"pw1"}If an object may be logged or sent over a network, define a toJSON() method that returns only the fields you want to expose. Do not rely on private to keep secrets out of output.
class SafeUser {
constructor(public name: string, private password: string) {}
toJSON(): { name: string } {
return { name: this.name };
}
}
console.log(JSON.stringify(new SafeUser("ann", "pw1"))); // {"name":"ann"}Exposing the internals through a getter
A private field can leak if a public method returns it directly and the value is mutable.
class Playlist {
private tracks: string[] = [];
add(track: string): void {
this.tracks.push(track);
}
getTracks(): string[] {
return this.tracks; // leaks the internal array
}
getTracksSafe(): readonly string[] {
return [...this.tracks]; // returns a copy
}
}
const list = new Playlist();
list.add("Intro");
list.getTracks().length = 0; // callers can empty the private array
console.log(list.getTracksSafe().length); // 0 only because we just emptied itprivate protects the reference stored in the field, not the object the reference points to. Return a copy, or a readonly view, when the value is mutable.
Losing this in callbacks
Private members are reached through this. If you pass a method as a callback, this is lost and the method fails when it touches a private field.
class Ticker {
private ticks = 0;
tick(): void {
this.ticks++;
}
tickArrow = (): void => {
this.ticks++;
};
getTicks(): number {
return this.ticks;
}
}
const ticker = new Ticker();
const detached = ticker.tickArrow;
detached();
console.log(ticker.getTicks()); // 1
// const broken = ticker.tick; broken(); // TypeError at runtime: this is undefinedThe arrow-function field keeps this bound to the instance. The regular method does not.
Choosing private
- Make a field
privatewhen its value must obey rules that only the class can check. - Make a method
privatewhen it exists only to help other methods in the class. - Prefer a small public API over many getters and setters. If every private field has a public getter and setter, the hiding adds nothing.
- Use
#privateinstead when you need protection that survives compilation.
Exercise
A class declares private items: string[] = [] and has a public method getItems(): string[] { return this.items; }. Code outside the class runs obj.getItems().push("x"). Does the compiler report an error, and does the class's private state change? How would you fix the class?
Show answer
The compiler reports no error, and the private array changes. private only prevents access to the items property itself. It does not protect the array object that the method returns. To fix it, return a copy (return [...this.items];) or declare the return type as readonly string[], and add a public addItem method for legitimate changes.
Exercise
Given class A { private id = 1; }, the expression new A()["id"] compiles and returns 1 even though id is private. Why does this work, and what does it tell you about using private for secrets?
Show answer
TypeScript allows bracket notation with a string literal as an intentional escape hatch, and private is removed when the code compiles to JavaScript. The property is an ordinary property at runtime. Therefore private guards against mistakes at compile time but cannot protect secrets. Use #private fields for runtime enforcement, and never store secrets in objects that may be logged or serialized.