Last updated: Feb 28, 2024
Reading time·2 min
// @ts-ignore
Use // @ts-ignore
to ignore the type checking errors on the next line in a
TypeScript file.
If you use a linter, you might have to add a comment to also suppress linting
errors when using ts-ignore
.
// eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore function sum(a, b) { return a + b; }
The // @ts-ignore
comment ignores all type-checking errors for a single line.
The function's parameters are not typed, however, no error is raised because we used the comment.
// @ts-expect-error
The @ts-expect-error comment can also be used to ignore errors for a single line.
// eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-expect-error function sum(a, b) { return a + b; }
The // @ts-expect-error
will ignore all type errors on the next line, but if
there aren't any errors, TypeScript will inform us that using @ts-expect-error
was unnecessary.
// eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-expect-error console.log('bobbyhadz.com' / 0); // ⛔️ Error: Unused '@ts-expect-error' directive.ts(2578) // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-expect-error console.log(100 * 100);
That's the main
difference between ts-ignore and ts-expect-error -
// @ts-ignore
doesn't alert us if the next line has no errors.
For example, you would use @ts-expect-error
if you have a function that takes
a parameter of type string
, but need to test it with parameters of different
types.
function logMessage(message: string) { if (typeof message !== 'string') { return 'message has to be a string'; } console.log(message); return message; } // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-expect-error const result = logMessage(42); if (result === 'message has to be a string') { console.log('test successful'); }
logMessage
function in the example takes a parameter of type string
. However, we want to test if the function does what we expect when invoked with a number
.If we don't add the @ts-expect-error
comment, we will get a type-checking
error, because the function expects a string
, and not a number
.
This way we can still test our function, and we will get alerted if there is no
need for a @ts-expect-error
comment.
I've also written a detailed guide on how to disable type checking for a file or a line in TS.
Use the @ts-nocheck comment to ignore all type-checking errors in a file.
// eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-nocheck function sum(a, b) { return a + b; }
You often have to ignore type-checking errors for an entire file when your project has type-checking for JavaScript files enabled.
If you don't use a linter or don't use any rules that prevent you from using ts comments, remove the line.