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

别说谁变了你拦得住时间么 提交于 2020-01-04 09:07:05

问题


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?


回答1:


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.


回答2:


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



回答3:


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



回答4:


Try

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


来源:https://stackoverflow.com/questions/53291780/error-after-updating-to-angular-7-argument-of-type-string-arraybuffer-is-no

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!