【问题标题】:How to add type to graphql schema using react and typescript?如何使用 react 和 typescript 将类型添加到 graphql 模式?
【发布时间】:2021-05-16 11:02:52
【问题描述】:

我有如下查询

query MyQuery($id: ID!) {
    something(id: $id) {
        details {
            id
            name
        }
    }
}

在 types.graphql 我有

type something {
    details: // this should either type details1 or type details2 
}

type details1 {
    id: string
    name: string
    description: string
}

type details2 {
    id: string
    name: string
    description: string
    other: string!
}

所以类型详细信息可以是类型 details1 或 details2

如何在 type something for details 字段中指定它。

有人可以帮我解决这个问题吗?谢谢。

编辑:

我尝试过类似下面的方法

type something {
    details : details1 | details2;
}

但这不起作用。

我能做的就是创造另一种类型

type details3 {
    id: string
    name: string
    description: string
    other: string
}

这是 details2 和 details3 的组合

并像使用它

type something {
    details: details3
}

但不想这样做。

【问题讨论】:

    标签: reactjs typescript graphql


    【解决方案1】:

    使用联合

    type something {
        details : details;
    }
    
    union details = details1 | details2
    

    【讨论】:

    • 谢谢。但是我如何阅读查询中的详细信息字段。我曾尝试使用联合,但它给出了错误无法查询类型 details1 或 details2 上的 id 和 name。你的意思是在 details1 或 details2 上使用内联片段
    • 是的,您使用内联片段在 details1 和 details 两个字段之间进行选择
    【解决方案2】:

    我认为您在定义类型时错过了= 符号, 我刚刚尝试过,它成功了:

    type details1 = {
        id: string
        name: string
        description: string
    }
    
    type details2 = {
        id: string
        name: string
        description: string
        other: string
    }
    
    type something = {
      details: details1 | details2;
    }
    
    const test: something = {
      details: {
        id: 'abc',
        name: 'abc',
        description: 'abc',
      }
    }
    
    
    const test2: something = {
      details: {
        id: 'abc',
        name: 'abc',
        description: 'abc',
        other: 'abc'
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-09-17
      • 1970-01-01
      • 2018-05-28
      • 2020-04-21
      • 2022-10-14
      • 2020-02-13
      • 2020-11-19
      • 2021-02-09
      • 2020-06-06
      相关资源
      最近更新 更多