【问题标题】:Type 'string | ArrayBuffer' is not assignable to type 'string'键入'字符串 | ArrayBuffer' 不可分配给类型 'string'
【发布时间】:2019-03-28 02:02:09
【问题描述】:

从 FileReader 读取字符串的 TypeScript 错误

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

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

我得到的 TypeScript 错误:

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

【问题讨论】:

  • reader.result 转换为string

标签: javascript typescript arraybuffer


【解决方案1】:

错误消息说明了一切。

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

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

const csv: string = reader.result as string;

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

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

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

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

【讨论】:

  • 你也可以像 const csv = reader.result.toString() 一样只做toString 它会处理所有事情,消除类型错误,并转换为字符串。
【解决方案2】:

无论csvstring 还是ArrayBuffer,这将始终输出一个字符串。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-12
    • 2020-05-30
    • 2021-08-19
    • 1970-01-01
    • 2021-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多