// TypeScript would flag: Argument of type 'string' is not assignable to parameter of type 'number'
// But at runtime the bug is silent — NaN is produced instead of an error
function calculateTotal(price, quantity) {
return price * quantity; // JS coerces string to number… sometimes
}
// Bug: price passed as string from a form input — not converted
const priceFromInput = '29.99'; // typeof === 'string'
const quantity = 3;
const total = calculateTotal(priceFromInput, quantity);
// Should be 89.97 but string * number behaves unexpectedly
console.log(total);
console.log(typeof total);function calculateTotal(price, quantity) {
return price * quantity;
}
// Fix: explicitly convert string to number before passing
const priceFromInput = '29.99';
const quantity = 3;
// TypeScript fix: annotate price as number and parse before calling
const total = calculateTotal(parseFloat(priceFromInput), quantity);
console.log(total.toFixed(2));
console.log(typeof total);Bug: In TypeScript this would be caught: string is not assignable to number. At runtime, JavaScript coerces "29.99" * 3 to a number and gets 89.97 — but relying on implicit coercion is fragile. The bug manifests with non-numeric strings.
Explanation: parseFloat converts the string to a proper number. TypeScript would enforce this with parameter type annotations — string would be rejected at compile time.
Key Insight: TypeScript type annotations prevent implicit type coercion bugs. Always annotate function parameters. When receiving values from external sources (forms, APIs), validate and convert before passing to typed functions.