3

I upgraded my project from angular 6 to angular 7. I have a file upload component in my project. It gives a compiler error after the upgrade.

onUpload() {
    const fileReader = new FileReader();
    fileReader.onload = () => this.uploadFile(fileReader.result);
    fileReader.readAsText(this.fileToUpload);
}

uploadFile(fileContent: string) {
    //upload
}

In above code, this.uploadFile(fileReader.result) gives following error.

error TS2345: Argument of type 'string | ArrayBuffer' is not assignable to parameter of type 'string'

The type of fileReader.result is string | ArrayBuffer, and it says this cannot be assigned to a string. How can I convert string | ArrayBuffer type to a string?

2
  • 1
    have you tried fileReader.result as string ? Commented Nov 14, 2018 at 1:23
  • @Zze it works. I didn't know about as string. Please add your comment as an answer. Commented Nov 14, 2018 at 1:30

4 Answers 4

14

Whilst result has the potential to return a string, it cannot implicitly cast this to a string as there is a risk of data loss. i.e. ArrayBuffer as string may result in data truncation (would have to test). So you have to explicitly cast it as to tell the compiler "I know what I am doing".

2 approaches to achieve this are:

(string)fileReader.result;
fileReader.result as string;


Folks, Check @Malvolio's answer, it's more complete.

Sign up to request clarification or add additional context in comments.

1 Comment

Malvolio's answer is more correct. This is just hiding the issue under the rug. When it comes back to bite you, you'll be wondering why it's not working: it's not working because you're lying to TypeScript.
3

You need a typeguard, like this:

if (this.fileToUpload instanceof ArrayBuffer) {
  // throw an error, 'cause you can't handle this
} else {
    fileReader.readAsText(this.fileToUpload);
}

Comments

1

You could use the method toString() to parse the result:

 const file = event.target.files[0];
 reader.readAsDataURL(file);

 const base64 = reader.result.toString().split(',')[1];

Comments

0

Try

fileReader.onload = () => this.uploadFile(<string>fileReader.result);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.