Borislav Hadzhiev
Sat Mar 12 2022·2 min read
Photo by Kevin Laminto
Use the // @ts-ignore
comment to disable type checking for a line in
TypeScript. The comment disables type checking for the next line. If you use a
linter, you might need to disable it for the line on which you use the
// @ts-ignore
comment.
// eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore function logMessage(message) { console.log(message); return message; }
The // @ts-ignore
comment disables all type checking for the next line.
If you need to disable type checking for an entire file, you can use the
// @ts-nocheck
comment.
// eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-nocheck function logMessage(message) { console.log(message); return message; }
The // @ts-nocheck
comment instructs TypeScript to skip type checking for the
entire file.
You might also see the @ts-expect-error comment being used to disable type checking for the next line.
// eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-expect-error console.log('hello world' / 0);
The // @ts-expect-error
will suppress any 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('hello world' / 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.
An example of when you would use the // @ts-expect-error
comment is when you
have a function that takes a parameter of a specific type, but want to test that
it works as expected when passed a parameter of a different type.
function sum(a: number, b: number) { if (typeof a !== 'number' || typeof b !== 'number') { return 0; } return a + b; } // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-expect-error const result = sum('hello', 'world'); if (result === 0) { console.log('✅ Test passes'); }
The sum
function in the example takes 2 numbers as parameters, but we want to
test if it works as expected when passed parameters of a different type.
// @ts-expect-error
comment, we would get a type checking error, because the function expects number parameters.Using this approach, we can test our function and would get a TypeScript error
if the // @ts-expect-error
comment was unnecessary.