可以使用 typescript 使 graphql 查询成为强类型吗?

Posted

技术标签:

【中文标题】可以使用 typescript 使 graphql 查询成为强类型吗?【英文标题】:Can make graphql query to be strongly types with typescript? 【发布时间】:2019-12-17 21:08:19 【问题描述】:

我正在使用 typescript 和 graphql,每次我想向我的 graphql 发送请求时,我都需要编写一个查询。

我的问题是无论如何都要使用类型/接口来创建查询?

例如看看这个界面:

interface Document 
  id: string;
  name: string;
  author: 
    name: string;
  

对此的graphql查询是

query document 
  id
  name
  author 
    name
  

我使用 axois 来获取数据:

const data = await axios.get("/graphql",  query );

有没有使用强类型获取数据的简单方法?类似:

const data = await axois.get('/graphql',  fields: ['id', 'name', 'author.name'] )

如果字段中的某些字符串不包含在界面中,打字稿将引发错误。

【问题讨论】:

【参考方案1】:

axios.get 可以采用泛型,它将提供返回类型上的类型。一个例子应该清楚。使用上面的代码

//                             vvvvvvvv==> your expected return data
const result = await axios.get<Document>("/graphql",  query );

// data will be strongly typed (but NOT checked)
result.data.id; // => string
result.data.author.name; // => string

更多信息请查看 axios 的index.d.ts 文件。

【讨论】:

以上是关于可以使用 typescript 使 graphql 查询成为强类型吗?的主要内容,如果未能解决你的问题,请参考以下文章

如何使用带有 Typescript 的泛型将中继(graphql)连接映射到边缘节点

如何为 TypeScript 配置 `*.graphql` 导入?

React Graphql Typescript 文件设置

在 gatsby 中将 typescript 标记的联合添加到 graphql 查询的结果

在生产问题中部署 Typescript GraphQL

使用 graphql 文件编译 Typescript 时出错