ReasonJun

What is "not assignable to parameter of type never" error in TypeScript? 본문

Frontend/Typescript

What is "not assignable to parameter of type never" error in TypeScript?

ReasonJun 2023. 7. 12. 23:20
728x90

The "not assignable to parameter of type never" error in TypeScript occurs when you try to assign a value of a type that is not never to a parameter of type never. The never type is a special type in TypeScript that represents a value that can never occur. This means that any attempt to assign a value of type never to a parameter of type never will result in an error.

 

For example, the following code will cause an error:

function neverFunction(value: never) {
  // ...
}

neverFunction(1); // Error: Argument of type '1' is not assignable to parameter of type 'never'

This is because the value 1 is of type number, and number is not a subtype of never. In other words, a number can always occur, but a value of type never can never occur.

There are a few ways to avoid this error. One way is to simply not use the never type. If you don't need to represent a value that can never occur, then you can use a different type, such as void.

Another way to avoid this error is to use a type guard. A type guard is a function that takes a value as input and returns a boolean indicating whether the value is of a certain type.

 

For example, the following type guard can be used to check if a value is of type never:

function isNever(value: any): value is never {
  return value === undefined || value === null;
}

This type guard can be used to avoid the error in the previous example as follows:

function neverFunction(value: never) {
  if (!isNever(value)) {
    throw new Error("Value is not of type never");
  }

  // ...
}

This code will only call the neverFunction function if the value passed to it is actually of type never. If the value is not of type never, then an error will be thrown.

728x90
Comments