【发布时间】:2018-11-24 19:52:38
【问题描述】:
我正在尝试让 Apollo 与 TypeScript 集成。 我有一个如下所示的 React 类:
interface Data {
allVendors: Array<VendorType>;
}
class AllVendorsQuery extends Query<Data> {}
const ShowVendors: React.SFC<> = props => {
return (
<AllVendorsQuery query={fetchVendors}>
{({ loading, error, data: { allVendors } }) => {
if (loading) {
return 'Loading...';
}
if (error) {
return `Error! ${error.message}`;
}
return (
allVendors &&
allVendors.map((vendor, index: number) => {
return (
<div key={`${vendor.name}_${index}`}>
#<strong>{vendor.id}</strong>
{vendor.name}
</div>
);
})
);
}}
</AllVendorsQuery>
);
};
export default ShowVendors;
查询是:
export default gql`
query GetVendors {
allVendors {
id
name
}
}
`;
TypeScript 抱怨 [ts] Type 'Data | undefined' has no property 'allVendors' and no string index signature. 出现在这一行:{({ loading, error, data: { allVendors } })。
但是,如果我使用 apollo-connect 而不是 Query 组件重构代码,我不会收到来自 TypeScript 的任何抱怨:
import { graphql, compose, QueryResult } from 'react-apollo';
interface ShowVendorsProps {
data: QueryResult & { allVendors?: VendorType[] };
}
class ShowVendors extends React.Component<ShowVendorsProps> {
render() {
const {
data: { allVendors }
} = this.props;
if (allVendors && allVendors.length > 0) {
return (
<div>
{allVendors.map((vendor, index: number) => {
return (
<div key={`${vendor.name}_${index}`}>
#<strong>{vendor.id}</strong>
{vendor.name}
</div>
);
})}
</div>
);
} else {
return 'Loading';
}
}
}
export default compose(graphql(fetchVendors))(ShowVendors);
这两者有什么区别?如何重写第一条语句的类型?
【问题讨论】:
标签: reactjs typescript apollo react-apollo