更新到 angular 7 后出错.'string | 类型的参数 |ArrayBuffer' 不可分配给类型为 'string' 的参数 [英] Error after updating to angular 7. Argument of type 'string | ArrayBuffer' is not assignable to parameter of type 'string'

查看:31
本文介绍了更新到 angular 7 后出错.'string | 类型的参数 |ArrayBuffer' 不可分配给类型为 'string' 的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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
}

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

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

错误 TS2345:'string 类型的参数 |ArrayBuffer' 不是可分配给字符串"类型的参数

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

fileReader.result 的类型是 string |ArrayBuffer,它说这不能分配给 string.如何转换 string |ArrayBuffer 类型为 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?

推荐答案

虽然 result 有可能返回一个字符串,但它不能将其隐式转换为字符串,因为存在数据丢失的风险.即 ArrayBuffer as string 可能会导致数据截断(必须测试).所以你必须明确地将它转换为告诉编译器我知道我在做什么".

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;

<小时>伙计们,检查@Malvolio 的答案,它更完整.


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

这篇关于更新到 angular 7 后出错.'string | 类型的参数 |ArrayBuffer' 不可分配给类型为 'string' 的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆