TypeScript Type Assertions
An assertion tells the checker to treat a value as a type. It does not validate, convert or repair that value, and it is erased from the emitted JavaScript.
How it works
Sometimes application setup has already established a fact the checker cannot see. Assertions can express that knowledge, but keeping the proof nearby makes review easier. This example first checks that a dictionary contains a finite numeric packet field, then uses a record view to read it. A dedicated type guard is usually clearer when the same boundary is used repeatedly.
Run the code
Try in playground loads this source without running it. Choose Run when ready. The existing TypeScript 5.8.3 worker transpiles and executes one file; it does not perform full semantic type checking, load npm imports or provide DOM/Node APIs. Use the local compiler for the type contract.
For a full check, save the three downloads together in a new folder, run npm install, then npm run check. Use npm run build followed by npm start to execute the checked JavaScript with Node. The supplied project enables strict checking, indexed-access checks and exact optional properties.
Example
const input: unknown = { packets: 8 };
if (typeof input !== "object" || input === null || !("packets" in input)) throw new Error("Missing packets");
const packets = (input as Record<string, unknown>)["packets"];
if (typeof packets !== "number" || !Number.isFinite(packets)) throw new Error("Invalid packets");
console.log(packets + 1);
Expected result
9
The runtime checks, rather than the assertion, make arithmetic legitimate. A double assertion through unknown could bypass compatibility checks without supplying any runtime evidence. When you see one, ask what invariant is missing from the model and whether a parser would make that contract explicit.