实现说明
除了类 InvoicePrinter、VatPrinter、LegacyPrinter,文件里再无其他定义。
演示用的数据放在这几个模块级绑定中:printer。
常见问题
复制和运行之间有安装步骤吗?
没有。从复制到运行之间没有别的要做。 文件的状态由几个模块级绑定持有:printer。
核心语句
return `${this.currency} ${(cents / 100).toFixed(2)}`;
return `total: ${this.format(cents)}`;
return super.format(withVat);
代码示例
class InvoicePrinter {
protected currency = 'USD';
format(cents: number): string {
return `${this.currency} ${(cents / 100).toFixed(2)}`;
}
summary(cents: number): string {
return `total: ${this.format(cents)}`;
}
}
class VatPrinter extends InvoicePrinter {
protected override currency = 'EUR';
private vatRate = 0.19;
override format(cents: number): string {
const withVat = Math.round(cents * (1 + this.vatRate));
return super.format(withVat);
}
}
const printer = new VatPrinter();
console.log(printer.summary(2500));
console.log(printer.format(2500));
class LegacyPrinter extends InvoicePrinter {
// 前提:TS4114(漏标 override)只在 noImplicitOverride 开启时才报,
// 下面的 @ts-expect-error 也只有在该旗标下才被消耗;默认 strict
// 不含此项,此时本指令反而报 TS2578 unused directive——
// 请以 --strict --noImplicitOverride 编译本片段。
// @ts-expect-error: TS4114 — missing override modifier
format(cents: number): string {
return 'legacy';
}
}
console.log(new LegacyPrinter().format(100));