Private Fields With Typed Accessors
Keep a class invariant with a #private field and a typed getter/setter pair, so every write path, method or direct assignment, passes the same validation.
Code
// 私有字段(#)与类型化访问器:不变量由 setter 统一把守
class Account {
#cents = 0;
readonly id: string;
constructor(id: string) {
this.id = id;
}
get balance(): number {
return this.#cents;
}
set balance(cents: number) {
if (!Number.isInteger(cents) || cents < 0) {
throw new RangeError('balance must be a non-negative integer');
}
this.#cents = cents;
}
deposit(cents: number): void {
this.balance = this.#cents + cents; // 走 setter 校验
}
}
const account = new Account('acc-1');
account.deposit(500);
console.log(`${account.id} balance=${account.balance}`);
try {
account.balance = -1;
} catch (error) {
console.log('rejected:', error instanceof RangeError ? error.message : String(error));
}Output
Captured from a sandboxed run of this snippet in the build pipeline.
acc-1 balance=500
rejected: balance must be a non-negative integerWhat the code does
The #cents private field carries the invariant: set balance rejects non-integers and negatives with RangeError, deposit routes its update through that same setter, and get balance is the only way back out.
RangeError is the guard’s signal — thrown at the branch, before any partial work happens.
The file’s state is a handful of top-level bindings: account.
Using it
The demo run deposits 500 and then assigns -1 directly, printing acc-1 balance=500 followed by rejected: balance must be a non-negative integer — the write path is the same whether the caller uses deposit or plain assignment.
Key statements
throw new RangeError('balance must be a non-negative integer');
return this.#cents;
Interactive Tools for This Topic
FAQ
- How are precondition violations signaled?
- The code throws `RangeError`. Handle it at the call site or let it propagate deliberately.
- Does the code pull in any external packages?
- No external packages are involved; every call resolves to a built-in API. Its state lives in module-level bindings: `account`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.