Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

typescript

Code is:

const foo = (foo: string) => {   const result = []   result.push(foo) } 

I get the following TS error:

[ts] Argument of type 'string' is not assignable to parameter of type 'never'.

What am I doing wrong? Is this a bug?

like image 880
Lev Avatar asked Sep 20 '18 11:09

Lev


People also ask

Is not assignable to parameter of type TypeScript?

The error "Argument of type string | undefined is not assignable to parameter of type string" occurs when a possibly undefined value is passed to a function that expects a string . To solve the error, use a type guard to verify the value is a string before passing it to the function.

Is not assignable to parameter of type type unknown?

The error "Argument of type 'unknown' is not assignable to parameter of type" occurs when we try to pass an argument of type unknown to a function that expects a different type. To solve the error, use a type assertion or a type guard when calling the function.

Is not assignable to parameter of type void TypeScript?

What is this? The error message "Argument of type 'void' is not assignable to parameter of type" means that we are passing an argument of type void to a function that expects a parameter of a different type. To solve the error, make sure to return a value from your functions. Copied!

What is the never type in TypeScript?

TypeScript introduced a new type never , which indicates the values that will never occur. The never type is used when you are sure that something is never going to occur. For example, you write a function which will not return to its end point or always throws an exception.


2 Answers

All you have to do is define your result as a string array, like the following:

const result : string[] = []; 

Without defining the array type, it by default will be never. So when you tried to add a string to it, it was a type mismatch, and so it threw the error you saw.

like image 58
Tha'er M. Al-Ajlouni Avatar answered Sep 24 '22 08:09

Tha'er M. Al-Ajlouni


Another way is :

const result = [] as  any; 
like image 27
neomib Avatar answered Sep 23 '22 08:09

neomib