首页 > 解决方案 > 对象可能为“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 的目的,因此我们将不胜感激任何帮助或提示!

标签: typescript

解决方案


推荐阅读