【问题标题】:Typescript Property 'label' does not exist on type 'string“字符串”类型上不存在 Typescript 属性“标签”
【发布时间】:2020-06-29 10:25:19
【问题描述】:

我使用下面的代码

    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 ...

更新

我尝试执行答案中的建议,但仍然遇到同样的错误

【问题讨论】:

    标签: javascript node.js typescript vscode-extensions


    【解决方案1】:

    在这种情况下,您需要区分联合类型中的两个可能值。

    例如,您可以确保该值不是字符串。这样打字稿将推断该值的类型为QuickPickItem

    interface State {     
      resourceGroup: QuickPickItem | string;   
    }
    
    let state: State = getState();
    
    if (typeof state.resourceGroup != 'string' && state.resourceGroup?.label){
      setEvent(...)
    }
    

    您可以在 typescript 手册中阅读更多相关信息。
    Type Guards and Differentiating Types

    【讨论】:

      【解决方案2】:

      最简单的方法是测试变量中是否存在label 属性:

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

      其他(不安全 - 所以只有当你 100% 确定你在做什么时)方法是使用感叹号手动断言该属性的存在:

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

      【讨论】:

      • 如果我像这样使用它if (state.resourceGroup.label) {我也遇到了错误(同样的错误)(property) resourceGroup?: string | QuickPickItem | undefined Object is possibly 'undefined'.ts(2532)
      • @BenoOdr 您还需要使用可选的链接运算符以避免未定义的问题if(state.resourceGroup?.label) { setEvent(state.resourceGroup.label).catch(err => console.error(err)); }
      • @eltonkamami ,当我这样做时if (state.resourceGroup?.label) { 我得到了同样的错误“属性“标签”不存在
      • 你可以用if(typeof state.resourceGroup != 'string') console.log(state.resourceGroup.label)确保它不是一个字符串
      • @eltonkamami - 行得通,您可以将其添加为答案,我目前使用的一个问题`if (typeof state.resourceGroup != 'string') { if (state.resourceGroup?.label) {是否有更短的方法来插入两个 if 语句?
      猜你喜欢
      • 2021-12-18
      • 2021-05-24
      • 1970-01-01
      • 2021-11-27
      • 2019-08-25
      • 2020-12-16
      • 2020-08-15
      • 2022-01-19
      • 2023-04-02
      相关资源
      最近更新 更多