[英]Typescript Property 'label' does not exist on type 'string
我使用以下代码
interface State {
resourceGroup: QuickPickItem | string;
}
setEvent(state.resourceGroup?.label).catch(err => console.error(err));
为此,我收到以下错误
any
Property 'label' does not exist on type 'string | QuickPickItem'.
Property 'label' does not exist on type 'string'.
https://code.visualstudio.com/api/references/vscode-api#QuickPickItem
知道如何避免这个错误吗? 不使用 ts-ignore 抑制它因为我无法更改QuickPickItem
...
更新
我尝试在答案中执行建议,但仍然遇到相同的错误
在这种情况下,您需要区分您拥有的联合类型中的两个可能值。
例如,您可以确保该值不是字符串。 这样 typescript 将推断该值是QuickPickItem
类型
interface State {
resourceGroup: QuickPickItem | string;
}
let state: State = getState();
if (typeof state.resourceGroup != 'string' && state.resourceGroup?.label){
setEvent(...)
}
您可以在 typescript 手册中了解更多信息。
类型保护和区分类型
最简单的方法是测试变量中是否存在label
属性:
if(state.resourceGroup.label) {
setEvent(state.resourceGroup.label).catch(err => console.error(err));
}
其他(不安全 - 所以只有当你 100% 确定你在做什么)方法是使用感叹号手动断言该属性的存在:
setEvent(state.resourceGroup.label!).catch(err => console.error(err));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.