Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
19
rated 0 times [  20] [ 1]  / answers: 1 / hits: 43605  / 6 Years ago, tue, october 23, 2018, 12:00:00

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'.

More From » typescript

 Answers
25

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() */}

[#53269] Thursday, October 18, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kaitlynnb

Total Points: 402
Total Questions: 96
Total Answers: 109

Location: Trinidad and Tobago
Member since Fri, May 8, 2020
4 Years ago
kaitlynnb questions
;