How to Fix “not assignable to parameter of type never” Error in TypeScript

To fix the “not assignable to parameter of type never” error in TypeScript, you can review your code and ensure the type inference is correct. If necessary, update your code to handle all cases and types correctly or explicitly specify the variable type instead of relying on type inference. This way, TypeScript will not infer the never type, and the error should disappear.

TypeScript raises “not assignable to parameter of type never” error when it infers that a variable should have the type never, but the code tries to assign a value of a different type to it. The never type in TypeScript represents a value that should never occur or a function that never returns (e.g., due to an infinite loop or throwing an error).

The error often happens when TypeScript’s type inference becomes too strict, such as when using discriminated unions or exhaustive type checks.

In these cases, TypeScript might infer that the type of a variable should be never, even though it’s not the intended behavior.

Example

Here’s an example to illustrate the issue and the solution.

type Fruit = "apple" | "banana" | "orange";

function getColor(fruit: Fruit): string {
  switch (fruit) {
    case "apple":
      return "red";
    case "banana":
      return "yellow";
  }
}

const color = getColor("orange");
console.log(color)

Output

not assignable to parameter of type never

# OR

undefined

In the above code example, TypeScript infers that the fruit parameter in the getColor() function should have the type never after handling the “apple” and “banana” cases in the switch statement. This leads to the error when calling getColor(“orange”).

To fix the error, you can update the switch statement to handle all cases:

type Fruit = "apple" | "banana" | "orange";

function getColor(fruit: Fruit): string {
  switch (fruit) {
    case "apple":
      return "red";
    case "banana":
      return "yellow";
    case "orange":
      return "orange";
   }
}

const color = getColor("orange");
console.log(color)

Output

orange

You can see that TypeScript can correctly infer the type of fruit, and the error disappears.

Leave a Comment