GraphQL打字稿参数类型不兼容

时间:2020-08-22 09:10:09

标签: typescript graphql typescript-typings react-apollo typescript-generics

我正在关注react tutorial。但是,似乎存在版本不匹配,我无法匹配我的类型。特别是,我的代码当前如下所示:

import * as React from "react";
import { graphql, ChildMutateProps } from "react-apollo";
import gql from "graphql-tag";
import {
  RegisterMutation,
  RegisterMutationVariables,
} from "./RegisterMutation";

interface Props {
  children: (data: {
    submit: (values: any) => Promise<null>;
  }) => JSX.Element | null;
}

export class C extends React.PureComponent<
  ChildMutateProps<Props, RegisterMutation, RegisterMutationVariables>
> {
  submit = async (values: any) => {
    console.log(values);

    const response = await this.props.mutate({ variables: values });
    console.log("response: ", response);

    return null;
  };

  render() {
    return this.props.children({ submit: this.submit });
  }
}

const registerMutation = gql`
  mutation RegisterMutation($email: String!, $password: String!) {
    register(email: $email, password: $password) {
      path
      message
    }
  }
`;

export const RegisterController = graphql(registerMutation)(C);

这会导致编译错误:

Argument of type 'typeof C' is not assignable to parameter of type 'ComponentType<Partial<DataProps<{}, {}>> & Partial<MutateProps<{}, {}>>>'.
  Type 'typeof C' is not assignable to type 'ComponentClass<Partial<DataProps<{}, {}>> & Partial<MutateProps<{}, {}>>, any>'.
    Types of parameters 'props' and 'props' are incompatible.
      Property 'children' is missing in type 'Partial<DataProps<{}, {}>> & Partial<MutateProps<{}, {}>>' but required in type 'Readonly<ChildMutateProps<Props, RegisterMutation, RegisterMutationVariables>>'.

尝试了可能的解决方案:

  1. 引入通用类型(>),最后一行上的graphql调用会引入更多类似性质的错误。
  2. 使用“ any”而不是RegisterMutation和RegisterMutationVariables进行键入会导致相同的错误,使我相信ChildMutateProps有所更改。

1 个答案:

答案 0 :(得分:0)

这是工作解决方案的外观,react-apollo/graphql已更改其键入。

// types
interface ComponentProps {
  children: (data: {
    submit: (values: any) => Promise<null>;
  }) => JSX.Element | null;
}

type WithMutateProps = ChildMutateProps<
  ComponentProps,
  RegisterMutation,
  RegisterMutationVariables
>;

// class definition
export class C extends React.PureComponent<WithMutateProps> { ...

// final controller
export const RegisterController = graphql<
  ComponentProps,
  RegisterMutation,
  RegisterMutationVariables,
  WithMutateProps
>(registerMutation)(C);