Lingua-e
← Errors
JavaScript

Type X is not assignable to type Y: What It Means and How to Fix It

Error reference

Type X is not assignable to type Y

Language

JavaScript

Severity

Medium

When it happens

This TypeScript compile error (TS2322) is reported when you try to assign a value of one type to a variable, parameter, or return type that expects a different, incompatible type.

Potential fixes

Align the type of the value with the type of the target. Change the variable's type annotation, update the function's return type, or convert the value. Avoid using type assertions (as) to silence this error: fix the types instead. Use union types (string | null) when a value can legitimately be one of several types.

Deep dive

This TypeScript compile error (TS2322) is reported when you try to assign a value of one type to a variable, parameter, or return type that expects a different, incompatible type. TypeScript's structural type system checks that the shape of the value matches what is expected.

Why it happens

  • Assigning the return value of a function to a variable declared with an incompatible type.
  • Passing an argument of the wrong type to a function parameter.
  • Returning a value from a function whose declared return type does not match.
  • Narrowing a union type incorrectly, leaving a type branch that does not satisfy the target type.

Potential fixes

Align the type of the value with the type of the target. Change the variable's type annotation, update the function's return type, or convert the value. Avoid using type assertions (as) to silence this error: fix the types instead. Use union types (string | null) when a value can legitimately be one of several types.

Examples

JavaScript

Code that triggers the error

function greet(name: string): string {
  return "Hello, " + name;
}

const result: number = greet("Alice");

Error output

error TS2322: Type 'string' is not assignable to type 'number'.

Fixed code

function greet(name: string): string {
  return "Hello, " + name;
}

const result: string = greet("Alice");
console.log(result);  // Hello, Alice

Practice in English

How would you explain a Type X is not assignable to type Y to a fellow dev? Choose the right phrase:

"I hit an error...

Ready to practice your English at work?

Lingua-e has interactive exercises built around real developer conversations: standups, code reviews, retrospectives, and more. Practice until it comes naturally.

Try Lingua-e for free