Type 'string' is not assignable to type 'number'. ts(2322)
You’re assigning a value that doesn’t match the expected type.
Fix 1: Match the types
// ❌ Type mismatch
let count: number = "5"; // string ≠ number
// ✅ Use the correct type
let count: number = 5;
// ✅ Or change the type annotation
let count: string = "5";
Fix 2: Handle union types
// ❌ string | undefined is not assignable to string
const name: string = user?.name; // Might be undefined!
// ✅ Provide a fallback
const name: string = user?.name ?? "Unknown";
// ✅ Or widen the type
const name: string | undefined = user?.name;
Fix 3: Object shape mismatch
interface User {
id: number;
name: string;
email: string;
}
// ❌ Missing required property
const user: User = { id: 1, name: "Alice" }; // Missing email!
// ✅ Include all required properties
const user: User = { id: 1, name: "Alice", email: "alice@example.com" };
// ✅ Or make email optional in the interface
interface User {
id: number;
name: string;
email?: string;
}
Fix 4: Array type mismatch
// ❌ number[] is not assignable to string[]
const items: string[] = [1, 2, 3];
// ✅ Match the types
const items: number[] = [1, 2, 3];
const items: string[] = ["a", "b", "c"];
Fix 5: Enum and literal types
// ❌ string is not assignable to "small" | "medium" | "large"
type Size = "small" | "medium" | "large";
const size: Size = someVariable; // someVariable is typed as string
// ✅ Assert the type (if you're sure)
const size: Size = someVariable as Size;
// ✅ Or validate first
if (someVariable === "small" || someVariable === "medium" || someVariable === "large") {
const size: Size = someVariable; // TypeScript narrows the type
}
When to use as (type assertion)
Only when you know more than TypeScript does:
const data = JSON.parse(text) as User; // You know the shape
const el = document.getElementById("app") as HTMLDivElement;
Don’t use as to silence errors you don’t understand — fix the actual type mismatch instead.
See also: TypeScript cheat sheet | Zod cheat sheet