typescript - 对象可能为“null”,类型为“as HTMLInputElement”,但不是“any”
问题描述
我在 Typescript 中有一个方法可以验证上传的文件大小和文件类型。
但是,我得到一个“对象可能是‘null’。每当我在 VSCode 上运行代码时都会出错。它发生在这一特定行:
const FileSize = (document.getElementById('fileName')as HTMLInputElement).files[0].size;
但是,当我将线路更改为
const FileSize = (document.getElementById('fileName')as any).files[0].size;
它似乎工作并且 TypeScript 错误被抑制。我不知道为什么,我很想知道为什么会发生这种情况。这是下面的完整方法:
private validateFileType() {
// Checks if file is .xsx or .xlsx
const masterFile = (document.getElementById('fileName')as HTMLInputElement).value;
const idxDot = masterFile.lastIndexOf('.') + 1;
const fileType = masterFile.substr(idxDot, masterFile.length).toLowerCase();
// Checks if file size is less than or equal to 5MB
const maxAllowedSize = 5 * 1024 * 1024;
const FileSize = (document.getElementById('fileName')as HTMLInputElement).files[0].size;
if (fileType !== 'xls' && fileType !== 'xlsx' ) {
// Alert code here
}
if (FileSize > maxAllowedSize) {
// Alert code here
}
}
我已经读过使用any
或强制转换以“欺骗”编译器会破坏使用 Typescript 的目的,因此我们将不胜感激任何帮助或提示!
解决方案
推荐阅读
- php - PHP:创建新对象时:对象中未定义的变量(但已明确定义)
- r - 这段代码中 b <-c() 的目的是什么?
- apache - 无法将参数传递到另一个重定向网站
- php - PHP foreach 循环不会显示不会将 JSON 文本打印到另一个显示基本画廊图像的 foreach 循环上
- postman - 无法从响应正文中检查 JSON 值
- c - 自定义 Shell Seg 错误
- html - 为什么我的阵列只在视图中更新一次?
- css - 在css中设置宽度100%后调整高度
- c++ - 从重载函数初始化 std::function 对象
- python - 如何解决在 Powershell Prompt 中运行 TabPy 时出现权限错误的问题