Published at
Updated at
Reading time
2min
This post is part of my Today I learned series in which I share all my web development learnings.

How do you deal with TypeScript when (for whatever reason) types are mixed up, everything's full of squigglies, but you're sure you want to ignore this one particular TypeScript error?

Let's look at a very simplified example; let's say you have a method taking in a string argument.

ts
function logify(msg: string) {
console.log(`Msg: ${msg}!`);
}

But you want to use the logify function with a number type. Of course, TypeScript won't be happy about you using logify with the wrong arguments. Still, you're 100% certain you want to call the function with a number type.

ts
logify(123);
Argument of type 'number' is not assignable to parameter of type 'string'.2345Argument of type 'number' is not assignable to parameter of type 'string'.

What can you do?

You can bring in your friends @ts-ignore and @ts-expect-error to silence TypeScript.

ts
// @ts-ignore
logify(123);
 
// @ts-expect-error
logify(123);

Both, @ts-ignore and @ts-expect-error, will make TypeScript ignore the type error happening on the following line. But which one should you use?

Generally, it's recommended to go for @ts-expect-error because it will lead to a TypeScript error when the following line isn't erroring anymore.

For example, it could be that the logify types will be changed to also accept numbers. Then, @ts-expect-error will let you know that you can remove it.

ts
// Let's allow number types... 👇
function logify(msg: string | number) {
console.log(`Msg: ${msg}!`);
}
 
// @ts-ignore
logify(123);
 
// @ts-expect-error
Unused '@ts-expect-error' directive.2578Unused '@ts-expect-error' directive.
logify(123);

The difference between the two comment directives is that @ts-expect-error forces you to clean up later. @ts-expect-error will let you know when there's no TypeScript error to silence and when it has become useless. @ts-ignore will stay put and sit silently wherever you placed it.

But whatever you choose, remember that you can extend @ts-comments as well. So, when you place them in your codebase, do yourself a favor and document why they're there.

ts
// @ts-ignore: `logify` should also allow numbers.
logify(123);
 
// @ts-expect-error: `logify` should also allow numbers.
logify(123);

That's it for today. ✌️

If you enjoyed this article...

Join 5.7k readers and learn something new every week with Web Weekly.

Web Weekly — Your friendly Web Dev newsletter
Reply to this post and share your thoughts via good old email.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles