@ts-expect-error Asserts Compile Failures
@ts-expect-error marks a line that must fail to compile, so a fixed bug or a loosened type turns the stale directive itself into a build error.
Code
interface Money {
cents: number;
currency: "USD" | "EUR";
}
function total(items: Money[]): number {
return items.reduce((sum, item) => sum + item.cents, 0);
}
// 负向类型测试:@ts-expect-error 断言下一行必须编译失败,失败消失即报错
// @ts-expect-error currency 不接受 "GBP"
const bad: Money = { cents: 100, currency: "GBP" };
// @ts-expect-error 缺少必填属性 cents
const partial: Money = { currency: "USD" };
const good: Money[] = [
{ cents: 1250, currency: "USD" },
{ cents: 499, currency: "EUR" },
];
console.log(`total cents: ${total(good)}`);
console.log(`bad currency: ${bad.currency}`);
console.log(`partial currency: ${partial.currency}`);
What the code does
All of the logic lives in the function total.
Points of care
- No install step: all APIs used ship with the platform.
Applying it
The main signature reads function total(items: Money[])
Output lines are prefixed (total cents: $, bad currency: $, partial currency: $), making each step’s effect easy to spot.
Statements that matter
return items.reduce((sum, item) => sum + item.cents, 0);
Interactive Tools for This Topic
A/B Test Sample Size CalculatorCalculate required per-variant sample size and experiment duration for two-proportion A/B tests from baseline conversion, MDE, alpha, and statistical power.JSONPath TesterTest JSONPath expressions against JSON documents with dot notation, brackets, wildcards, and recursive descent.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Which packages does this snippet need?
- None. Every symbol the code uses resolves inside the standard library. The file defines `total` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.