首页 > 解决方案 > 打字稿和处理 FileReader

问题描述

我正在尝试将客户端上的文件作为数组缓冲区读取。这是我的代码。

for (var index = 0; index < input.files.length;index++) {
  let reader = new FileReader();
  console.log(input.files[index].name);
  reader.onload = () => {
    var data:ArrayBuffer = reader.result;
    console.log(data.toString().length);
  }
  reader.readAsArrayBuffer(input.files[index])
}

但是我的编辑抱怨 reader.result 返回 (string | ArrayBuffer)

但是,如果我从数据中删除类型类型。我无法使用 ArrayBuffer 特定的方法,如 byteLength。

如何强制 reader.result 成为 ArrayBuffer?

标签: typescript

解决方案


好吧,您知道 TS 是相当不错的 xD。像平常一样编写代码,它会解释你的代码,事情就会发生。

function foo() {
    return (
        Math.random() < 0.5
            ? "damn dis shit wild"
            : new ArrayBuffer(1024)
    )
}

let bar = foo(); // string | ArrayBuffer
if (bar instanceof ArrayBuffer) {
    // bar is only ArrayBuffer in this block :O *.*
    bar.byteLength; // <-- no error
} else {
    bar.startsWith("damn") // <-- no error
}

这是一个演示。我想这就是你想要的?

顺便说一句,您还提到了“强制”,所以正常的断言也可以工作,但不建议这样做,因为如果bar是的话,它会给出运行时错误string

function foo() {
    return (
        Math.random() < 0.5
            ? "damn dis shit wild"
            : new ArrayBuffer(1024)
    )
}

let bar = <ArrayBuffer>foo();
bar.byteLength; // <-- no error

演示


推荐阅读