← 中文资源

简体中文版本

构造函数重载接受多种形态

一个类挂多个构造签名、共用一份实现:调用方传原始字段或已解析记录都保持类型正确,实现签名对外不可见,分支判断收口在类内部完成。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

inv-1 4950 false
inv-2 1250 true

实现说明

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);