Skip to main content

Expect errors, don't ignore them

Nov 11, 2022

A nifty TypeScript best practice that often slips under the radar, the choice between @ts-expect-error and @ts-ignore when dealing with TypeScript errors.

We all want to write robust, error-free code. When it comes to suppressing those inevitable errors, precision is key. That’s where @ts-expect-error shines.

With @ts-expect-error, you’re not just sweeping errors under the rug. You’re explicitly saying, “Hey TypeScript, I know there’s an issue here, and I expect it. Let’s move on.” It’s like putting a sign on a pothole, ensuring you won’t forget to fix it later.

Unlike the broader strokes of @ts-ignore, @ts-expect-error narrows down the suppression to the exact line where you foresee trouble. This level of specificity keeps your codebase cleaner and minimizes the chances of overlooking potential pitfalls.

Here is an example on a simple use case

//@ts-expect-error: Intentional suppression of error here
const id: number = 'I am a string';

This snippet tells TypeScript, “I’m aware this might cause issues, but I’ve got it covered.” It’s a simple yet powerful way to communicate your intent to both the code and your fellow developers.

Small decisions can make a big impact. So, the next time you find yourself reaching for a suppression comment, consider the use of @ts-expect-error. It’s a subtle shift that can lead to a more resilient and maintainable codebase.