Sub topic 15
Assertions and `@ts-expect-error`: When and How
Assume you know TypeScript annotations, interfaces, unions, and basic compiler commands. This chapter focuses on cases where the compiler lacks information, or where a type error is intentional and tested.
Type assertions change the compiler's view
A type assertion tells TypeScript to treat a value as a particular type:
const value: unknown = "hello";
const text = value as string;
console.log(text.toUpperCase());The assertion does not convert or validate the value at runtime. If value is actually a number, text.toUpperCase() can still fail while running. An assertion only changes static checking.
Use an assertion when you have stronger information than the compiler and can explain why that information is reliable. For example, a DOM lookup may be known to return a particular element:
const button = document.querySelector("#save") as HTMLButtonElement;
button.disabled = true;This assertion is unsafe if the element is missing or has a different type. A safer alternative checks the value:
const element = document.querySelector("#save");
if (!(element instanceof HTMLButtonElement)) {
throw new Error("Save button was not found");
}
element.disabled = true;Prefer validation, narrowing, or a corrected type annotation when those options are available.
`unknown` is safer than an assertion
Values from JSON, request bodies, and external libraries often have uncertain types. unknown forces you to check before using a value.
function readName(value: unknown): string {
if (
typeof value === "object" &&
value !== null &&
"name" in value &&
typeof value.name === "string"
) {
return value.name;
}
throw new Error("Expected an object with a string name");
}
console.log(readName({ name: "Ada" }));An assertion would be shorter, but it would trust input that has not been checked.
Use `@ts-expect-error` for intentional errors
@ts-expect-error suppresses the diagnostic on the next line. Unlike @ts-ignore, it also reports an error if the next line no longer produces a diagnostic.
function double(n: number): number {
return n * 2;
}
// @ts-expect-error: this test confirms strings are rejected
double("21");This is useful in type-level tests and compatibility tests. The comment documents the expected failure. If a future change makes double("21") valid, TypeScript reports an unused @ts-expect-error, prompting you to update the test.
Use it narrowly. Do not place it above a large block, because unrelated errors can become hidden. Fix ordinary application errors instead of suppressing them.
| Choice | Use it when | Main risk |
|---|---|---|
| Narrowing | You can check the value at runtime | Requires validation code |
| Type annotation | The intended type is known at the source | May reveal more errors |
| Assertion | A trusted invariant is unavailable to TypeScript | No runtime safety |
| `@ts-expect-error` | A specific failure is intentional and tested | Can hide a changed expectation |
Exercise
Why is @ts-expect-error usually safer than @ts-ignore for a deliberate type error?
Show answer
It suppresses the expected diagnostic but becomes a new diagnostic if the following line stops producing an error.