Lahiru Chandima
Lahiru Chandima

Reputation: 24068

Error after updating to angular 7. Argument of type 'string | ArrayBuffer' is not assignable to parameter of type 'string'

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?

Upvotes: 3

Views: 12676

Answers (4)

Zze
Zze

Reputation: 18805

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.

Upvotes: 14

gorums
gorums

Reputation: 1737

Try

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

Upvotes: 0

J C
J C

Reputation: 761

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];

Upvotes: 1

Michael Lorton
Michael Lorton

Reputation: 44386

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);
}

Upvotes: 3

Related Questions