【问题标题】:Receiving type-checking error from root query based on the type I assign to my root nodes. GraphQL, TypeScript. Express根据我分配给根节点的类型,从根查询接收类型检查错误。 GraphQL,打字稿。表示
【发布时间】:2021-06-03 04:54:53
【问题描述】:

我对 typescript/graphql 世界很陌生,当我定义我的一个根节点的类型时,我收到了一个奇怪的错误。我正在实现的根节点只是在解析函数中按 ID 返回用户,因此,我正在使用我创建的 UserType 填充“类型”键。但是,我从打字稿中得到一个错误提示

fields: Thunk<GraphQLFieldConfigMap<TSource, TContext>>;
              ~~~~~~
        The expected type comes from property 'fields' which is declared here on type 'Readonly<GraphQLObjectTypeConfig<any, any>>'

rootQuery.ts 文件:

import mongoose from "mongoose";
import { GraphQLObjectType, GraphQLString } from "graphql";

const UserType = "./user_type.ts";
const User = mongoose.model("user");

const RootQueryType = new GraphQLObjectType({
  name: "RootQueryType",
  fields: () => ({
    getUserById: {
      type: UserType,
      args: {
        id: { type: GraphQLString },
      },
      async resolve(_, { id }) {
        try {
          return await User.findById(id);
        } catch (err) {
          console.error(err.message);
        }
      },
    },
  }),
});

module.exports = RootQueryType;

user_type.ts 文件:

import { GraphQLObjectType, GraphQLString, GraphQLList } from 'graphql'

const UserType = new GraphQLObjectType({
    name: 'User',
    fields: () => ({
        name: { type: GraphQLString },
        email: { type: GraphQLString },
        password: { type: GraphQLString },
        language: { type: GraphQLString },
        topics: { type: new GraphQLList(GraphQLString)}
    })
})

module.exports = UserType;

错误指向 RootQueryType 中的“字段”键。当我用 'GraphQLString' 替换 'getUserById' 节点中的 'type' 键的值时,错误消失了。但显然这不是我想要的,因为返回值将被引用到 UserType。

感谢您的宝贵时间。

【问题讨论】:

    标签: typescript express graphql typeerror


    【解决方案1】:

    我发现这是我在 rootQuery.ts 文件中导入/需要 graphql 包的方式。我没有导入,而是将其更改为:

    const graphql = require('graphql')
    const { GraphQLObjectType, GraphQLString } = graphql;
    

    但我不明白为什么。 require 与 import 相比如何导致错误?

    【讨论】:

      猜你喜欢
      • 2019-01-02
      • 2020-04-23
      • 1970-01-01
      • 1970-01-01
      • 2022-11-04
      • 1970-01-01
      • 1970-01-01
      • 2016-06-08
      • 2020-06-21
      相关资源
      最近更新 更多