A type assertion tells the compiler "trust me, this value is of type X" using as. It does no runtime conversion or checking — it only changes how the compiler treats the value.
ts
el = .() ;
el. = ;
data = .(str) ;
A type assertion tells the compiler "trust me, this value is of type X" using as. It does no runtime conversion or checking — it only changes how the compiler treats the value.
el = .() ;
el. = ;
data = .(str) ;
An assertion overrides the compiler's judgment — if you're wrong, you get a runtime crash with no warning:
const x = "hello" as unknown as number; // double assertion — compiler stops complaining
x.toFixed(2); // 💥 runtime error: x.toFixed is not a function
Asserting doesn't make the value that type; it just silences the checker. You've taken responsibility for correctness away from the compiler.
// 1. type guard — actually verify at runtime
if (typeof input === "string") { /* input is string, proven */ }
// 2. validation library (zod) for external data
const user = UserSchema.parse(data); // throws if shape is wrong
as const is differentconst point = { x: 1 } as const; // not a risky cast — narrows to literal/readonly
Assertions are sometimes necessary (DOM APIs, narrowing unknown you've already checked), but each one is a place the compiler can't protect you.
Prefer type guards or schema validation for untrusted data, and treat every as as a small, deliberate "I know better" that you must be sure about.