The difference between @ts-ignore and @ts-expect-error
- Published at
- Updated at
- Reading time
- 2min
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
functionlogify (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
Argument of type 'number' is not assignable to parameter of type 'string'.2345Argument of type 'number' is not assignable to parameter of type 'string'.logify (123 );
What can you do?
You can bring in your friends @ts-ignore
and @ts-expect-error
to silence TypeScript.
ts
// @ts-ignorelogify (123);// @ts-expect-errorlogify (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... 👇functionlogify (msg : string | number) {console .log (`Msg: ${msg }!`);}// @ts-ignorelogify (123);Unused '@ts-expect-error' directive.2578Unused '@ts-expect-error' directive.// @ts-expect-error 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. ✌️
Join 5.7k readers and learn something new every week with Web Weekly.