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

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

问题描述

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

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:字符串|类型"的参数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种方法是:

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天全站免登陆