【发布时间】:2018-07-04 14:40:42
【问题描述】:
我正在尝试使用 apollo-client 和 TypeScript 构建一个简单的 React 组件。
这个组件只是查询文章列表并显示它们。代码如下:
import * as React from 'react';
import graphql from "react-apollo/graphql";
import { ARTICLES_FEED } from "../schemas/queries";
import { Article, ArticlesFeedResponse } from "../schemas/results";
import { ChildProps } from "react-apollo/types";
const AppQL = graphql<ArticlesFeedResponse, {}>(ARTICLES_FEED);
class App extends React.Component<ChildProps<{}, ArticlesFeedResponse>, {}> {
render() {
const { loading, feed, error } = this.props.data;
if (loading) return <div>loading</div>;
if (error) return <div>{ error }</div>;
return (
<React.Fragment>
<h1>It works!</h1>
{this.props.data && feed.map( (article:Article) => (
<div>{article.shortText}</div>
))}
</React.Fragment>
);
}
}
export default AppQL(App);
模式/结果:
export interface Article {
id: string,
shortText: string,
publicationDate: string
}
export type ArticlesFeedResponse = {
feed: Article[];
}
模式/查询:
import gql from 'graphql-tag'
export const ARTICLES_FEED = gql`
query ArticlesFeed {
feed {
id
shortText
publicationDate
}
}
`;
尽管如此,签名匹配,但我仍然收到错误:
Type '(QueryProps<OperationVariables> & Partial<ArticlesFeedResponse>) | undefined' has no property 'loading' and no string index signature.
我不明白发生了什么 - 导入的类型是:
ChildProps:
export declare type ChildProps<P, R> = P & {
data?: QueryProps & Partial<R>;
mutate?: MutationFunc<R>;
};
查询属性:
export interface QueryProps<TVariables = OperationVariables> {
error?: ApolloError;
networkStatus: number;
loading: boolean;
variables: TVariables;
fetchMore: (fetchMoreOptions: FetchMoreQueryOptions & FetchMoreOptions) => Promise<ApolloQueryResult<any>>;
refetch: (variables?: TVariables) => Promise<ApolloQueryResult<any>>;
startPolling: (pollInterval: number) => void;
stopPolling: () => void;
subscribeToMore: (options: SubscribeToMoreOptions) => () => void;
updateQuery: (mapFn: (previousQueryResult: any, options: UpdateQueryOptions) => any) => void;
}
所以ChildProps 应该同时包含loading 和error 属性。我猜| undefined 部分有一个错误,但我不明白为什么会出现这个联合。
有什么建议吗?
P。 S. 如果我不从react-apollo/types 导入默认ChildProps,而是使用这个更新版本:
type ChildProps<P, R> = P & {
data: QueryProps & R;
mutate?: MutationFunc<R>;
};
我的代码正在运行。我仍然没有得到的是 - 我做错了什么还是react-apollo/types 包中的错误?
【问题讨论】:
标签: typescript react-apollo apollo-client