Type assertions
Concept and syntax
A type assertion x as T changes how the checker treats an expression; it neither converts nor validates its runtime value. Assertions are accepted only within certain compatibility boundaries. Prefer narrowing when the actual value is uncertain, and use an assertion only when you have independent evidence.
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 raw:unknown="7";const asserted=raw as number;console.log(typeof asserted,Number(raw)+1);Expected output:
string 8The asserted variable is still the string "7"; runtime typeof therefore reports string. Number(raw) actually performs a conversion, so adding 1 yields 8. For untrusted values, check the conversion before using it.
Common mistake
Intentionally invalid; compile separately and do not execute.
Expected diagnostic: TS2352. The direct assertion has insufficient overlap. If conversion is intended, use Number and validate the result.
Practice and recap
Compare an assertion with Number("bad") and a finite-number check.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Type 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 raw:unknown="7";const asserted=raw as number;console.log(typeof asserted,Number(raw)+1);Which diagnostic and explanation match the rejected example under the lesson settings?
const x="7" as number;