πŸ”§ Error Fixes
Β· 2 min read
Last updated on

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

πŸ“˜