问题
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