Debugging
Error Playground
Every TypeScript developer meets these errors. Learn to read them like the compiler intended — problem, reason, and the proper fix.
TS2322: Type 'string' is not assignable to type 'number'
You declared that a variable, property, or return value has one type, but the value you are assigning has another. It shows up constantly with form inputs, JSON, and environment variables, because everything coming from those sources is a string even when it looks like a number.
Triggers the error
interface Product {
name: string;
price: number;
}
const input = document.querySelector("input");
const product: Product = {
name: "Coffee",
price: "4.50", // Error: Type 'string' is not assignable to type 'number'
};Fixed
interface Product {
name: string;
price: number;
}
const raw = "4.50";
const price = Number(raw);
if (Number.isNaN(price)) {
throw new Error("Invalid price input");
}
const product: Product = {
name: "Coffee",
price, // now a real number
};Why the compiler complains
TypeScript enforces assignment compatibility: a value can only be assigned to a target if its type is a subset of the target's type. The string "4.50" carries no guarantee it can behave like a number — you cannot multiply it or pass it to Math functions — so the compiler rejects the assignment at the exact line where the mismatch is introduced, instead of letting it explode later at runtime.
How to fix it properly
Convert the value at the boundary where it enters your program: use Number(value) or parseFloat(value), and handle the NaN case if the input might not be numeric. Do not silence the error with 'as unknown as number' — a cast changes what the compiler believes, not what the value is, so the string sails through and breaks arithmetic later. If a field genuinely can be either, declare it as string | number and narrow before use.