46

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'.
Krupal Panchal
  • 1,553
  • 2
  • 13
  • 26
Aragorn
  • 5,021
  • 5
  • 26
  • 37

2 Answers2

69

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() */}
Nurbol Alpysbayev
  • 19,522
  • 3
  • 54
  • 89
  • 5
    You could also just do `toString` anyway like `const csv = reader.result.toString()` It takes care of everything, silencing the type error, and converting to string anyway. – Nishant Jun 29 '20 at 07:16
4

This will always output a string regardless if csv is a string or an ArrayBuffer.

const csv: string = typeof csv === 'string' ? csv : Buffer.from(csv).toString()
villy393
  • 2,985
  • 20
  • 28