Type Assertions
TS · Type Annotationssyntax
value as Type
<Type>value // not in JSX filesexample
const rawData = JSON.parse(payload) as { userId: string; role: string };
// HTMLElement narrowing
const canvas = document.getElementById("game") as HTMLCanvasElement;
const ctx = canvas.getContext("2d");
// Double assertion for incompatible types (use sparingly)
const weird = ("hello" as unknown) as number;output
// Assertions override the compiler — they do NOT perform runtime conversionNote Type assertions are a compile-time escape hatch — no runtime checking or conversion happens. If you assert incorrectly, you get silent bugs. Prefer type guards (typeof, instanceof) when possible. The angle-bracket syntax <Type>value conflicts with JSX — always use 'as Type' in .tsx files.