Sub topic 14
Type assertions and their risks
This chapter assumes you know basic TypeScript annotations, union types, and the unknown type. You should also be comfortable reading compiler errors from tsc or your editor.
A type assertion tells the compiler to treat a value as a specific type. You write it with the as keyword. The compiler accepts your claim without checking it at runtime, so the assertion only changes what the compiler believes. The JavaScript that runs is unchanged.
const data = JSON.parse('{"id": 7}') as { id: number };
console.log(data.id.toFixed(1)); // prints "7.0"This works because the JSON really contains a number. If the JSON were wrong, the compiler would not notice.
const bad = JSON.parse('{"id": "7"}') as { id: number };
console.log(bad.id.toFixed(1)); // compiles, then throws a TypeError at runtimeThe compiler accepts both versions. Only the second one crashes, and it crashes at runtime, far from the line that made the mistake.
Where the compiler stops you
The compiler rejects an assertion when the two types have no overlap. This check catches obvious mistakes:
const n = "5" as number;
// Error: Conversion of type 'string' to type 'number' may be a mistakeThe check only compares types that are clearly unrelated. A wrong claim about a type that overlaps with the real one passes without complaint.
Prefer unknown and narrowing
When a value comes from outside your code, type it as unknown and check its shape. The compiler then forces the check before you use the value.
function isUser(value: unknown): value is { id: number } {
return (
typeof value === "object" &&
value !== null &&
"id" in value &&
typeof value.id === "number"
);
}
const parsed: unknown = JSON.parse('{"id": "7"}');
if (isUser(parsed)) {
console.log(parsed.id.toFixed(1));
} else {
console.log("Invalid user data"); // this branch runs
}The value is { id: number } return type is a type predicate. It tells the compiler what the check proves. The checks inside the function still have to be correct, because the compiler trusts them.
flowchart TD
A[Value from outside code] --> B{Checked at runtime?}
B -- Yes --> C[Narrowed type, safe to use]
B -- No, only asserted with as --> D[Unchecked type]
D --> E[Runtime error if the claim is wrong]Common errors
- Using
asto silence an error. The error usually points to a real mismatch. Fix the type, or add a check. - Asserting
anyvalues.anyturns off checking, so the assertion adds no protection. - Double assertions. Writing
x as unknown as Tbypasses the overlap check completely. Use it only when you can prove the value's shape. - Assuming a type predicate checks more than it does. The compiler trusts your predicate body, so a wrong check leads to wrong types.
> The safest assertion is the one you never need to write.
interface Config {
port: number;
}
function readPort(raw: unknown): number {
if (typeof raw === "object" && raw !== null && "port" in raw && typeof raw.port === "number") {
return raw.port;
}
throw new Error("port must be a number");
}Exercise
Exercise
The following code compiles without error. Why does it crash at runtime, and how would you change it so the compiler requires a check first? const payload = JSON.parse('{"count": "3"}') as { count: number }; console.log(payload.count.toFixed(2));
Show answer
The assertion tells the compiler that count is a number, but JSON.parse returns the string "3". Calling toFixed on a string throws a TypeError. To fix it, declare the parsed result as unknown, then check typeof payload.count === "number" inside an if block before using it.