Suppression directives
Concept and syntax
A // @ts-expect-error comment suppresses a diagnostic on the next line and reports an unused directive if no diagnostic occurs. // @ts-ignore suppresses without that unused check. Prefer expect-error for intentional negative type tests, but remember it does not identify the exact error or make the code safe to execute.
Working example
Save each snippet separately as main.ts in a fresh directory. Compile with tsc --strict --target ES2022 --module commonjs --moduleDetection force --skipLibCheck --noEmitOnError main.ts, then run the accepted example with node main.js. Forced module detection isolates snippet names from global declarations.
function take(n:number){return n;}if(false){ // @ts-expect-error intentionally wrong argument take("bad");}console.log(take(7));Expected output:
7Comparison with ts-ignore
This separate valid line has an unnecessary ts-ignore comment. No unused-directive diagnostic is emitted; the output is 7. Replace the comment with ts-expect-error and TS2578 is reported.
Common mistake
Intentionally invalid; compile separately and do not execute.
Expected diagnostic: TS2578. The following line is valid, so the expectation is unused. Remove the directive or restore the intended negative test.
Practice and recap
Fix a negative example and observe how expect-error notices that the error disappeared.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Suppression directives — knowledge check
Check the contract, trace output, and diagnose an invalid example.
Which statement about this lesson’s concept is accurate?
What is the complete stdout, represented as a JSON string (including newline characters)?
function take(n:number){return n;}if(false){ // @ts-expect-error intentionally wrong argument take("bad");}console.log(take(7));Which diagnostic and explanation match the rejected example under the lesson settings?
// @ts-expect-errorconst n:number=7;