Type 'string' is not assignable to type 'number'
TypeScript caught a type mismatch.
Why this happens
TypeScript uses structural typing to verify that values match their declared types at compile time. When you assign a value of one type to a variable expecting a different type, the compiler rejects it. This catches bugs before runtime that JavaScript would silently allow.
Fix 1: Fix the type
// β Wrong type
let count: number = "5";
// β
Correct type
let count: number = 5;
// β
Or parse it
let count: number = parseInt("5");
Fix 2: Update the type definition
// β
Allow both types with a union
interface Config {
port: number | string;
}
Fix 3: Use type assertion (last resort)
const value = someFunction() as string;
β οΈ Only use this when youβre sure about the type.
Alternative solutions
Use type guards to safely narrow types at runtime:
function processValue(input: string | number) {
if (typeof input === 'string') {
return input.toUpperCase();
}
return input * 2;
}
Prevention
- Enable
strict: trueintsconfig.jsonfrom the start β retrofitting strict mode is harder. - Avoid
any. Useunknownwhen the type is genuinely uncertain, then narrow with type guards.
Related resources
Related: TypeScript: No Overload Matches This Call Β· What is TypeScript