实现说明
Invoice定义了示例的行为。
各个操作都建立在顶层绑定之上:fromParts、fromRow。
常见问题
复制和运行之间有安装步骤吗?
没有。从复制到运行之间没有别的要做。 文件用顶层绑定保存自己的状态:fromParts、fromRow。
核心语句
this.paid = idOrRow.paid ?? false;
this.paid = paid ?? false;
this.cents = cents ?? 0;
代码示例
type LedgerRow = { id: string; cents: number; paid?: boolean };
class Invoice {
readonly id: string;
readonly cents: number;
paid: boolean;
// Overload 1: raw parts
constructor(id: string, cents: number, paid?: boolean);
// Overload 2: an already-parsed record
constructor(row: LedgerRow);
// Implementation signature is invisible to callers
constructor(idOrRow: string | LedgerRow, cents?: number, paid?: boolean) {
if (typeof idOrRow === 'string') {
this.id = idOrRow;
this.cents = cents ?? 0;
this.paid = paid ?? false;
} else {
this.id = idOrRow.id;
this.cents = idOrRow.cents;
this.paid = idOrRow.paid ?? false;
}
}
}
const fromParts = new Invoice('inv-1', 4950, false);
const fromRow = new Invoice({ id: 'inv-2', cents: 1250, paid: true });
console.log(fromParts.id, fromParts.cents, fromParts.paid);
console.log(fromRow.id, fromRow.cents, fromRow.paid);