实现说明
主体是 Account。
失败是响亮的:RangeError 在守卫分支上直接中止当前操作,不做降级。
顶层就这几处状态:account。
使用要点
- 直接运行文件,输出会带上标签,比如
rejected:——输出的每一行都能指回产生它的那次调用。
常见问题
前置条件不满足时如何报错?
代码会抛出 RangeError。请在调用点处理,或有意让它向上传播。
这段代码会引入外部包吗?
不涉及外部包,每个调用都落在内建 API 上。 文件用顶层绑定保存自己的状态:account。
核心语句
throw new RangeError('balance must be a non-negative integer');
return this.#cents;
代码示例
// 私有字段(#)与类型化访问器:不变量由 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));
}