typescript - 打字稿和处理 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?
解决方案
好吧,您知道 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
推荐阅读
- sql - 如何使用 SELECT * INTO(PIVOT Result 查询)创建具有透视结果的表
- c++ - 我可以将 CPLEX 更改为 CBC 求解器吗?
- image - PayPal NVP 标题图像 (HDRIMG)
- oracle - 根据开始日期和结束日期拆分日期
- azure-timeseries-insights - Time Series Insight AutoRest 错误:插件模型验证器报告失败
- java - Graphviz 绘制的图有不必要的边缘交叉
- django - 使用 Django + Docker 在 VScode 中丢失代码导航
- javascript - HTML:我应该将样式放在内部元素还是周围的 div 元素上?
- java - Glassfish 5.1 无法添加资源
- c# - 用于创建通讯组列表的 Outlook 加载项(实时和桌面)