Fix: TypeScript TS2322 β Type 'X' is not assignable to type 'Y'
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
Related: What is TypeScript