更新到 angular 后出错 7. 'string | ArrayBuffer' 类型的参数不能分配给 'string' 类型的参数

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

我将我的项目从 angular 6 升级到 angular 7。我的项目中有一个文件上传组件。升级后出现编译错误。

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

uploadFile(fileContent: string) {
    //upload
}

在上面的代码中,this.uploadFile(fileReader.result) 给出了以下错误。

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

fileReader.result的类型是string | ArrayBuffer,它说这不能分配给string。如何将 string | ArrayBuffer 类型转换为 string

虽然 result 有可能 return 一个字符串,但它不能隐式地将其转换为一个字符串,因为存在数据丢失的风险。即 ArrayBuffer as string 可能会导致数据截断(必须进行测试)。所以你必须显式地转换它来告诉编译器 "I know what I am doing".

实现此目的的 2 种方法是:

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


伙计们,检查@Malvolio 的答案,它更完整。

你需要一个 typeguard,像这样:

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

您可以使用方法 toString() 来解析结果:

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

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

尝试

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