πŸ”§ Error Fixes
Β· 1 min read

TypeScript: Type X Is Not Assignable to Type Y β€” How to Fix It


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: true in tsconfig.json from the start β€” retrofitting strict mode is harder.
  • Avoid any. Use unknown when the type is genuinely uncertain, then narrow with type guards.

Related: TypeScript: No Overload Matches This Call Β· What is TypeScript

πŸ“˜