@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.

TypescriptData Integrity

Code

typescriptsnippet
24 lines
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

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.