Typescript - 如何解决“Type 'undefined' is not assignable to type 'XXXX'”?

Typescript - How to solve " Type 'undefined' is not assignable to type 'XXXX' "?

我用一些属性定义了接口。尝试访问该服务时出现此错误 - 类型 'undefined' 在 this.isOpen 的显示文件中不可分配。我需要帮助来解决这个错误。

注意 - 我无法在配置文件中设置值,例如 "strictNullChecks":false

界面

export interface DataFile {
  file?: DataFile[];
  location: string;
}

打字稿class


  isOpen?: DataFile;

  Scan(aero: string, TeamClass: string) {
    if (TeamClass === 'Hawkins') {
      if (this.redService.name.file && this.redService.name.file.length > 0) {
        this.isOpen = this.redService.name.file.filter((data: DataFile) => data.location == aero[0])[0];
      }
    }
    
    this.displayfile(this.isOpen).then(async () => {  ----->>>>>> Error at this.isOpen
            //rest of the functionality
        }
      }
    });
  }

我遇到错误-

 Argument of type 'DataFile | undefined' is not assignable to parameter of type
'DataFile'.
  Type 'undefined' is not assignable to type 'DataFile'.

通过设置带有问号的 isOpen,它会选择两种类型:一种是 DataFile(您的类型)和 undefined。这就是Typescript报错的主要原因。

要解决它,您有两个选择:

  • 检查 isOpen 是否填充了数据,即:
if (!isOpen) { /* do something */ }
...rest of code
  • isOpen 前加上 !(即 this.isOpen!),这样您就可以强制类型不被定义。不推荐,因为如果它确实未定义,您将 运行 在 this.displayfile 函数中出错。

此处关于问号运算符的参考:https://www.geeksforgeeks.org/why-use-question-mark-in-typescript-variable/