我的vscode中出现以下错误:

[ts] Property 'getPatientAllAddress' does not exist on type 'Object'.

为什么要检查动态添加的getPatientAlladdress()方法?
这通常不会发生在Javascript中。
get addresses() {
    if (this.data && this.data.hasOwnProperty("getPatientAllAddress")) {
        return this.data.getPatientAllAddress();
    }
}

如何压制/忽略这个警告。

最佳答案

到目前为止,this.data已经有了Object类型。发生此错误的原因是您试图访问.getPatientAllAddress()类型变量的Object属性。即使您已经在逻辑上证实它应该具有该属性,编译器仍然不够聪明,应该理解它应该使该属性在该变量的接口上可用。
解决方案1
如果您没有打开noImplicitAny标志,您应该可以将最后一行更改为

return data['getPatientAllAddress']();

解决方案2
this.data的类型设置为:{getPatientAllAddress?:Function}(或者在更好的环境中创建与this.data相对应的接口,该接口包含该函数)。
使用函数或适当的更具体的类型。
解决方案3
定义完整数据的接口
interface Bleh {
    getPatientAllAddress : Function
}

和一个类型警卫
function isBleh(x:any) : x is Bleh {
    return x && x.hasOwnProperty("getPatientAllAddress");
}

并用作
if (isBleh(this.data)) {
    this.data.getPatientAllAddress();
}

解决方案1是最简单的,解决方案2是最正确的(尽管你也应该真正定义接口中的其他任何东西,而不仅仅是这个可选函数),解决方案3是我展示语言特征的一半,并且半讲一下在1和2不可行的情况下你需要做的事情。

10-05 21:09
查看更多