Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type 'string | ArrayBuffer' is not assignable to type 'string'

TypeScript error for reading string from FileReader

Simple code to read file contents:

const reader: FileReader = new FileReader();        reader.readAsText(file);        reader.onload = (e) => {           const csv: string = reader.result; -> getting TS error on this line } 

TypeScript error I get:

Type 'string | ArrayBuffer' is not assignable to type 'string'.   Type 'ArrayBuffer' is not assignable to type 'string'. 
like image 643
Aragorn Avatar asked Oct 23 '18 18:10

Aragorn


People also ask

How do I fix string null is not assignable to type string?

The "Type 'string | null' is not assignable to type string" error occurs when a possibly null value is assigned to something that expects a string . To solve the error, use a non-null assertion or a type guard to verify the value is a string before the assignment.

Is not assignable to type string?

The "Type 'string' is not assignable to type" TypeScript error occurs when we try to assign a value of type string to something that expects a different type, e.g. a more specific string literal type or an enum. To solve the error use a const or a type assertion.

How do I fix type string is not assignable to type never?

The error "Type is not assignable to type 'never'" occurs when we declare an empty array without explicitly typing it and attempt to mutate the array. To solve the error, explicitly type the empty array, e.g. const arr: string[] = []; .

Is not assignable to type any undefined?

The "Type 'undefined' is not assignable to type" error occurs when a possibly undefined value is assigned to something that expects a different type. To solve the error, use the non-null assertion operator or a type guard to verify the value is of the specific type before the assignment.


1 Answers

The error message says it all.

You declare a string type of csv variable. You then assign string | ArrayBuffer type (of reader.result) to the string type, you just assigned. You cannot. You only can assign string to string.

So, if you 100% sure that reader.result contains string you could assert this:

const csv: string = reader.result as string; 

However if you are not sure, do this:

const csv: string | ArrayBuffer = reader.result; // or simply: const csv = reader.result; // `string | ArrayBuffer` type is inferred for you 

Then you typically should have some check like:

if (typeof csv === 'string') {/*use csv*/} else {/* use csv.toString() */} 
like image 141
Nurbol Alpysbayev Avatar answered Sep 23 '22 13:09

Nurbol Alpysbayev