简体   繁体   English

Typescript 类型“字符串”上不存在属性“标签”

[英]Typescript Property 'label' does not exist on type 'string

I use the following code我使用以下代码

    interface State {
        resourceGroup: QuickPickItem | string;

    }

setEvent(state.resourceGroup?.label).catch(err => console.error(err));

And for it I got the following error为此,我收到以下错误


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 https://code.visualstudio.com/api/references/vscode-api#QuickPickItem

Any idea how to avoid this error?知道如何避免这个错误吗? without suppressing it with ts-ignore As im not able to change the QuickPickItem ...不使用 ts-ignore 抑制它因为我无法更改QuickPickItem ...

update更新

I try to do the suggestion in the answer and still got the same error我尝试在答案中执行建议,但仍然遇到相同的错误

在此处输入图像描述

在此处输入图像描述

In this case you will need to differentiate between the two possible values in the union type you have.在这种情况下,您需要区分您拥有的联合类型中的两个可能值。

For example you can make sure that the value is not a string.例如,您可以确保该值不是字符串。 that way typescript will infer that the value is of type QuickPickItem这样 typescript 将推断该值是QuickPickItem类型

interface State {     
  resourceGroup: QuickPickItem | string;   
}

let state: State = getState();

if (typeof state.resourceGroup != 'string' && state.resourceGroup?.label){
  setEvent(...)
}

You can read more about it in the typescript handbook.您可以在 typescript 手册中了解更多信息。
Type Guards and Differentiating Types 类型保护和区分类型

Easiest is to test for the existence of the label property in your variable:最简单的方法是测试变量中是否存在label属性:

if(state.resourceGroup.label) {
   setEvent(state.resourceGroup.label).catch(err => console.error(err));
}

Other (unsafe - so only if you are 100% sure what you are doing) way is to use the exclamation mark to assert the existence of the porperty manually:其他(不安全 - 所以只有当你 100% 确定你在做什么)方法是使用感叹号手动断言该属性的存在:

setEvent(state.resourceGroup.label!).catch(err => console.error(err));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM