简体   繁体   English

GraphQL 查询返回类型的“任何”数据类型

[英]"Any" data type for GraphQL Query Return Type

I am a bit new to Typescript and am having some issues with data types.我对 Typescript 有点陌生,并且在数据类型方面遇到了一些问题。 I was told that I should avoid using the 'any' data type since it negates the whole point of using Typescript.有人告诉我,我应该避免使用“任何”数据类型,因为它否定了使用 Typescript 的全部意义。 However, I am unable to change the data types.但是,我无法更改数据类型。 For example,例如,

when I run a GraphQL query, I use this:当我运行 GraphQL 查询时,我使用这个:

   login({
      variables: {
        email: email,
        password: password,
      },
    })
      .then(({ data }: any) => {
        localStorage.setItem('token', data.loginEmail.accessToken);
        setShouldRedirect(true);
        //props.history.push("/panel");
      })

The data.loginEmail.accessToken is a string so I changed :any to string but I get errors that: data.loginEmail.accessToken是一个字符串,所以我将:any更改为字符串,但出现以下错误:

Argument of type '({ data }: string) => void' is not assignable to parameter of type '(value: ExecutionResult<any>) => void | PromiseLike<void>'.
  Types of parameters '__0' and 'value' are incompatible.
    Type 'ExecutionResult<any>' is not assignable to type 'string'.  TS2345

If I change the type to object , I get Property 'data' does not exist on type '{}'. TS2339如果我将类型更改为object ,我会Property 'data' does not exist on type '{}'. TS2339得到Property 'data' does not exist on type '{}'. TS2339 Property 'data' does not exist on type '{}'. TS2339 but the documentation also says that the mutation returns an object. Property 'data' does not exist on type '{}'. TS2339但文档还说突变返回一个对象。 So if not object or string, how else could I specify the data type for such an object?因此,如果不是对象或字符串,我还能如何为此类对象指定数据类型? Is it even possible?甚至有可能吗?

Similarly, when I map items like this after a query:同样,当我在查询后映射这样的项目时:

{data &&
          data.users.nodes &&
          data.users.nodes.map((c: any, i: any) => (
            <li key={i}>
              Id: {c.id}, First Name: {c.firstName}, Last Name: {c.lastName},
              Email: {c.email}, phoneNumber: {c.phoneNumber}
            </li>
          ))}

How else could I specify c and I?我还能如何指定 c 和 I? There's no simple integer option for i. i 没有简单的整数选项。

Edit:编辑:

Schema:架构:

  loginEmail(
    email: String!
    password: String!
  ): SignInResponse!
type SignInResponse {
  accessToken: String!
}

GraphQL Code: GraphQL 代码:

export type MutationLoginEmailArgs = {
  email: Scalars['String'],
  password: Scalars['String']
};

If you're using TypeScript, you should generate the types for both the data returned by the hook and the variables you pass to it.如果您使用的是 TypeScript,您应该为钩子返回的数据和传递给它的变量生成类型。 Type generation can be done using either the Apollo CLI or GraphQL Code Generator .类型生成可以使用Apollo CLIGraphQL 代码生成器来完成

Once you've got your types, you can then use them with your hooks as shown here in the docs .获得类型后,您可以将它们与钩子一起使用,如文档中所示。 By doing this, you will avoid having to explicitly assign types when consuming the data property returned by the hook.通过这样做,您将避免在使用钩子返回的data属性时必须显式分配类型。 You will also add type safety for any variables passed to the hook.您还将为传递给钩子的任何变量添加类型安全性。

Example usage from the docs:文档中的示例用法:

interface RocketInventory {
  id: number;
  model: string;
  year: number;
  stock: number;
}

interface RocketInventoryData {
  rocketInventory: RocketInventory[];
}

interface RocketInventoryVars {
  year: number;
}

const GET_ROCKET_INVENTORY = gql`
  query getRocketInventory($year: Int!) {
    rocketInventory(year: $year) {
      id
      model
      year
      stock
    }
  }
`;

export const SomeComponent = () => {
  const { loading, data } = useQuery<RocketInventoryData, RocketInventoryVars>(
    GET_ROCKET_INVENTORY,
    { variables: { year: 2019 } }
  );
  ...
}

Looks like your data structure corresponds to the following type interface:看起来您的数据结构对应于以下类型接口:

interface MyDataReponse {
  users: {
   nodes: {
    id: string; // maybe this is number in your case
    firstName:string;
    lastName: string;
    phoneNumber: string;
    email: string;
   }[]
  }
}

Then on your data:然后在您的数据上:

.then(({ data }: ExecutionResult<{data:MyDataReponse;}>) => {

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 GraphQL Blackbox / “任何”类型? - GraphQL Blackbox / “Any” type? 当没有数据返回时,GraphQL 变异返回类型应该是什么? - What should be the GraphQL mutation return type when there is no data to return? 如何在graphql中获取查询的类型名称 - How to get the type names of the query in graphql 如何在 GraphQL (Relay) 中查询和改变数组类型? - How to query and mutate array type in GraphQL (Relay)? Apollo客户端Graphql查询变量类型错误 - Apollo client Graphql query variable type error GraphQL 查询中的错误显示未知类型“ContentfulSizes” - Error in GraphQL query it says Unknown type "ContentfulSizes" 您的 GraphQL 查询中出现错误:无法在“StrapiPropiedadesImagen”类型上查询字段“childImageSharp” - There was an error in your GraphQL query: Cannot query field “childImageSharp” on type “StrapiPropiedadesImagen” 如何在Graphql中返回JSON对象并定义JSON类型 - How can I return a JSON object in Graphql and define JSON type 输入'{数据:InvitedUser[]; ““: 任何; }' 不可分配给类型 'Element' - Type '{ data: InvitedUser[]; “”: any; }' is not assignable to type 'Element' GraphQL:Query.type 字段类型必须是输出类型但得到:未定义 - GraphQL: Query.type field type must be Output Type but got: undefined
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM