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
Type 'string | ArrayBuffer' is not assignable to type 'string'
提问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 string
type of csv
variable.
You then assign string | ArrayBuffer
type (of reader.result
) to the string
type, you just assigned. You cannot. You only can assign string
to string
.
您声明了一种string
类型的csv
变量。然后将string | ArrayBuffer
type (of reader.result
)分配给string
刚刚分配的类型。你不能。您只能分配string
给string
.
So, if you 100% sure that reader.result
contains string
you 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 csv
is a string
or an ArrayBuffer
.
这将始终输出一个字符串,无论csv
是 astring
还是 an ArrayBuffer
。
const csv: string = typeof csv === 'string' ? csv : Buffer.from(csv).toString()