Sub topic 15
Assertions and @ts-expect-error: when and how
This chapter assumes you can already read a diagnostic (file, position, code, message), know why a value is or is not assignable to a type, and can fix an error by narrowing or by changing an annotation. Here you will learn the two tools you use when none of those fixes fits: type assertions and suppression comments. Both change what the compiler reports. Neither changes what your program does at runtime.
What an assertion does
A type assertion tells the compiler to treat an expression as a type you name. It is written value as Type. The compiler stops checking that claim. It also emits nothing for it, so the generated JavaScript has no conversion, no check, and no error if you are wrong.
interface User {
id: number;
name: string;
}
const raw = '{"id": 1}';
const data: unknown = JSON.parse(raw);
const user = data as User;
console.log(user.name.toUpperCase());This compiles without errors. At runtime it throws TypeError: Cannot read properties of undefined (reading 'toUpperCase'), because the parsed object has no name. The assertion moved the failure from compile time to runtime.
The compiler does not accept every assertion. It requires the two types to overlap enough that one could plausibly be the other:
const n = "5" as number;src/index.ts(1,11): error TS2352: Conversion of type 'string' to type 'number' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.The message offers the escape: "5" as unknown as number. That double assertion compiles, and it is almost always wrong. When you see TS2352, treat it as the compiler telling you the value really is a different type. The fix here is Number("5"), a real conversion.
Prefer a check over a claim
If the type of a value comes from outside your program (JSON, user input, a network response), check it instead of asserting it. A type guard is a function whose return type is value is Type. It performs a runtime test, and the compiler trusts the result inside the if.
interface User {
id: number;
name: string;
}
function isUser(value: unknown): value is User {
return (
typeof value === "object" &&
value !== null &&
"id" in value &&
typeof value.id === "number" &&
"name" in value &&
typeof value.name === "string"
);
}
const data: unknown = JSON.parse('{"id": 1}');
if (isUser(data)) {
console.log(data.name.toUpperCase());
} else {
console.log("Not a valid user");
}This relies on in narrowing unknown, which needs TypeScript 4.9 or later. The program now prints Not a valid user instead of crashing. For larger shapes, a schema validation library does the same job with less code.
The non-null assertion
The postfix ! removes null and undefined from a type. It is an assertion with the same trade-off: nothing checks it at runtime.
const stock = new Map<string, number>();
stock.set("apple", 3);
const apples = stock.get("apple")!;
console.log(apples + 1);This is defensible when an invariant that the compiler cannot see guarantees the value exists, here the set call on the line above. Where the invariant is weaker, throw an explicit error and let narrowing do the work:
const pears = stock.get("pear");
if (pears === undefined) {
throw new Error("Expected pear stock to be set");
}
console.log(pears + 1);The second version fails with a message that names the problem. The ! version would print NaN and continue.
`satisfies` as a middle path
Sometimes you reach for an assertion only to check that an object matches a type. The satisfies operator checks the type but keeps the narrower inferred type, so nothing is silenced:
type Config = { retries: number; mode: "fast" | "safe" };
const config = { retries: 3, mode: "fast" } satisfies Config;
console.log(config.mode);If mode were "slow", this line would report an error. An as Config assertion would have accepted a mismatch of that kind, as long as the types overlap enough.
Suppressing a diagnostic with @ts-expect-error
A suppression comment hides the diagnostics on the next line. Use // @ts-expect-error rather than // @ts-ignore. The difference is what happens when the error goes away:
| Directive | Hides errors on next line | If no error occurs there |
|---|---|---|
| `// @ts-ignore` | Yes | Nothing. The stale comment stays silently. |
| `// @ts-expect-error` | Yes | Reports TS2578: Unused '@ts-expect-error' directive. |
The second behavior is the reason to prefer it. The comment documents a known error, and the compiler tells you when it is no longer needed. The legitimate case is a test that checks a bad input is rejected:
function double(n: number): number {
return n * 2;
}
// @ts-expect-error: string input must be rejected
double("21");Suppose someone later widens double to accept number | string. The call is now valid, so the compiler reports:
src/index.ts(5,1): error TS2578: Unused '@ts-expect-error' directive.That prompts you to remove the comment or revisit the test. With @ts-ignore, the test would pass without complaint while checking nothing.
Gotchas with suppression comments
The directive covers one line, the line directly after it. A multi-line statement often reports the error on a later line, so the comment appears to do nothing and you get two errors: the original and TS2578.
type Config = { retries: number; mode: "fast" | "safe" };
function run(config: Config): void {
console.log(config.retries, config.mode);
}
run({
// @ts-expect-error: retries is deliberately a string in this test
retries: "3",
mode: "fast",
});The error is reported at the retries property, so the comment sits directly above it. Placed above run({, it would have missed.
The directive also hides every error on that line, not just the one you meant. If you later add a second mistake to the same line, such as a misspelled function name, the comment hides it too. Keep suppressed lines short, and keep the failing expression isolated.
Write a reason after the directive. Teams usually enforce this with the @typescript-eslint/ban-ts-comment lint rule, which can be set to allow directives only when they have a description.
Choosing between the options
The order below matches how much information you give up. Start at the top and move down only when the earlier options do not fit.
Use these rules of thumb:
- Assert only when you can state, in a comment, why the value has that type.
- Assert at a boundary, once, and give the result a precise name. Do not scatter assertions through business logic.
- Use
@ts-expect-errorfor deliberate misuse in tests and for confirmed bugs in third-party type definitions. Link the issue in the comment. - Never use
as anyto quiet an error. It disables checking for everything the value touches, and the damage spreads downstream.
Auditing what you have
Assertions and suppressions are debt, and you can search for them. A command such as grep -rn "@ts-expect-error\|@ts-ignore" src lists every suppression. When you revisit an old one, delete the comment and run npx tsc --noEmit. If the error returns, read it again. The surrounding code or the library types may have changed enough that a real fix is now possible.
Exercise
A teammate writes const port = process.env.PORT as number; and the compiler reports TS2352. Why does it refuse the assertion, and what is a correct fix?
Show answer
process.env.PORT has type string | undefined, and number does not sufficiently overlap with it, so the compiler flags the assertion as a likely mistake. Even a forced as unknown as number would leave a string (or undefined) at runtime. The correct fix is a real conversion with a check, for example const port = Number(process.env.PORT); if (Number.isNaN(port)) { throw new Error("PORT must be a number"); }.
Exercise
You add // @ts-expect-error above a call that spans four lines, and tsc now reports both the original error and TS2578. What is happening, and how do you fix it?
Show answer
The directive only covers the next line, but the error is reported on a later line of the call (for example, on one argument or property). The directive therefore suppresses nothing and is reported as unused. Move the comment to the line directly above the one where the original error is reported, or restructure the code so the failing expression sits on one line.