Double assertions
Concept and syntax
An assertion through unknown can bypass a direct compatibility restriction: value as unknown as T. This is a type-system escape hatch, not a conversion. It can describe a runtime value incorrectly. Prefer parsing and validation at boundaries; reserve double assertions for rare, independently justified cases.
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.
The accepted example deliberately exposes a static-safety limitation. Do not imitate the unsafe path in production.
const unsafe="7" as unknown as number;const parsed=Number("7");console.log(typeof unsafe,Number.isFinite(parsed),parsed+1);Expected output:
string true 8Common mistake
Intentionally invalid; compile separately and do not execute.
Expected diagnostic: TS2352. The direct assertion is rejected because the primitive types do not overlap sufficiently. Parse instead of bypassing the check.
Practice and recap
Replace the double assertion with a function accepting unknown and returning a validated number.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Double assertions — 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)?
const unsafe="7" as unknown as number;const parsed=Number("7");console.log(typeof unsafe,Number.isFinite(parsed),parsed+1);Which diagnostic and explanation match the rejected example under the lesson settings?
const unsafe="7" as number;