我有一些属性定义的接口。尝试访问该服务时,出现此错误-显示文件中的“未定义”类型不可分配this.isOpen
。我需要帮助来解决此错误。
注意-我无法在配置文件中设置值,例如 "strictNullChecks":false
接口
export interface DataFile {
file?: DataFile[];
location: string;
}
打字稿课
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/
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句