Explicit Override On Class Members
Mark members that replace base-class implementations with override so accidental shadows and signature drift fail compilation under noImplicitOverride.
Code
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));How the snippet works
Count the classes InvoicePrinter, VatPrinter and LegacyPrinter as the entire surface area of Explicit Override On Class Members.
Everything operates on top-level bindings: printer.
Statements that matter
return `${this.currency} ${(cents / 100).toFixed(2)}`;
return `total: ${this.format(cents)}`;
return super.format(withVat);
Interactive Tools for This Topic
FAQ
- Is there an install step between copy and run?
- No. Between copying and running there is nothing left to do. Its state lives in module-level bindings: `printer`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.