【问题标题】:unable to access types that implement a interface while parsing data from GraphQL query在解析来自 GraphQL 查询的数据时无法访问实现接口的类型
【发布时间】:2020-04-28 01:06:38
【问题描述】:

我有一个为 graphql 片段查询自动生成的 methodsfragment.ts 文件。我使用了命令npm run generate --graphql

在查询中,我们有一个 formElement 接口,它可以是基于数据的输入、选择、单选等。数据看起来像这样:

    inputs[{
     formElements:{
        identifier: "first_name_input",
        label: "First name",
         placeholder: "" 
}
},{
formElement:{
  identifier: "select_year",
  label: "year",
  options:["1999","2000", "2001"]
}}]

在我的 methodsFragments.ts 中,我有 formElements 的定义,例如:

export type inputRows_formElements = inputRows_formElements_firstNameInputField | inputRows_formElements_yearDropdown;

type  firstNameInputField {
 identifier: string!;
 label: string!;
 placeholder: string!;
}

type yearDropdown {
   identifier: string!;
   label: string!;
   options: string[];

}

当我尝试访问数据时,我会执行以下操作:

methods.map(formEle) =>{
  switch(formEle.identifier):
    case "select_year" :
      console.log("options length" + formEle.options); // at this line i get the error 
}

错误消息是:“类型 inputRows_formElements 上不存在属性选项”。我不确定如何解决此错误。

【问题讨论】:

    标签: reactjs typescript graphql


    【解决方案1】:

    要解决此错误,请使用 trypescript 中提供的 as 关键字。因此,当您访问选项的数据时,您可以执行以下操作:

    methods.map(formEle) => {
      switch(formEle.identifier):
        case "select_year" :
          let curElement = formEle as inputRows_formElements_yearDropdown
          console.log("options length" + formEle.options); 
    }
    

    这应该可以解决这个问题。

    【讨论】:

      猜你喜欢
      • 2019-09-26
      • 2022-07-24
      • 1970-01-01
      • 2022-08-02
      • 2020-07-12
      • 2021-12-16
      • 2020-12-01
      • 2017-08-17
      • 2023-03-04
      相关资源
      最近更新 更多