Predict the output · TypeScript
Type Assertions Don't Convert
Easy Predict the output Seen at Microsoft, Stripe, Atlassian
What does this print?
What does this print?
const input: unknown = "42";
const n = input as number;
console.log(n + 1, typeof n);
43 number
421 string
43 string
NaN number
Check your answer
Loading the editor… (JavaScript is required to run code in your browser.)
Solution
Show the answer
The output is:
421 string
as is a compile-time instruction to trust you; no conversion happens. At runtime n is still the string "42", so + 1 concatenates. Validate or convert unknown data explicitly (Number(input), a schema library like Zod) instead of asserting.
More Gotchas problems
- var in a Loop with setTimeout · Easy
- Microtasks vs Macrotasks · Medium
- Type Coercion Surprises · Medium
- Numeric Enums at Runtime · Medium
- readonly and as const at Runtime · Medium
- Mutable Default Arguments · Easy