typescript 输入'字符串| ArrayBuffer' 不可分配给类型 'string'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52955710/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:41:46  来源:igfitidea点击:

Type 'string | ArrayBuffer' is not assignable to type 'string'

javascripttypescriptarraybuffer

提问by Aragorn

TypeScript error for reading string from FileReader

从 FileReader 读取字符串的 TypeScript 错误

Simple code to read file contents:

读取文件内容的简单代码:

const reader: FileReader = new FileReader();
       reader.readAsText(file);
       reader.onload = (e) => {
          const csv: string = reader.result; -> getting TS error on this line
}

TypeScript error I get:

我得到的打字稿错误:

Type 'string | ArrayBuffer' is not assignable to type 'string'.
  Type 'ArrayBuffer' is not assignable to type 'string'.

回答by Nurbol Alpysbayev

The error message says it all.

错误消息说明了一切。

You declare a stringtype of csvvariable. You then assign string | ArrayBuffertype (of reader.result) to the stringtype, you just assigned. You cannot. You only can assign stringto string.

您声明了一种string类型的csv变量。然后将string | ArrayBuffertype (of reader.result)分配给string刚刚分配的类型。你不能。您只能分配stringstring.

So, if you 100% sure that reader.resultcontains stringyou could assert this:

因此,如果您 100% 确定reader.result包含string您可以断言:

const csv: string = reader.result as string;

However if you are not sure, do this:

但是,如果您不确定,请执行以下操作:

const csv: string | ArrayBuffer = reader.result;
// or simply:
const csv = reader.result; // `string | ArrayBuffer` type is inferred for you

Then you typically should have some check like:

那么您通常应该进行一些检查,例如:

if (typeof csv === 'string') {/*use csv*/}
else {/* use csv.toString() */}

回答by villy393

This will always output a string regardless if csvis a stringor an ArrayBuffer.

这将始终输出一个字符串,无论csv是 astring还是 an ArrayBuffer

const csv: string = typeof csv === 'string' ? csv : Buffer.from(csv).toString()