我已经关注了一些有关GraphQL的博客教程,并且能够将我的GraphQL查询与应该显示返回结果的React组件结合在一起。当我执行this.props
的console.log时,此方法有效。
下一步,我实际上想引用props(由GraphQL放置在其中)中的各个数据成员-之类的props.Security.loading
-这就是所有内容的分解之处。
理想情况下,我只想在键入中的某处使用“ any”并避免这种麻烦,但是我也可以在接口中显式指定所有可以返回的数据(我认为这样会打败GraphQL的目的)。那么我该怎么做呢?看来,当我在Props接口中注释掉“数据:安全性”这一行时,代码就会编译。在这里彻底困惑。谢谢
import * as React from "react";
import { gql } from "apollo-boost";
import { graphql } from "react-apollo";
const getSymbolInfoQuery = gql` {
Security(id: "MSFT") {
id
}
} `;
interface Security {
loading: Boolean;
}
interface Props {
data: Security
}
class ProductChecker extends React.Component<Props, {}> {
constructor(props: Props) {
super(props);
console.log(props);
}
render() {
return <div>{this.displaySearchFilters()}</div>;
}
displaySearchFilters() {
console.log(this.props);
return (
<div>Hello there</div>
);
}
}
export default graphql(getSymbolInfoQuery)(ProductChecker);
最后“导出”行上的错误:
Error: [ts]
Argument of type 'typeof ProductChecker' is not assignable to parameter of type 'ComponentType<Partial<DataProps<{}, {}>> & Partial<MutateProps<{}, {}>>>'.
Type 'typeof ProductChecker' is not assignable to type 'ComponentClass<Partial<DataProps<{}, {}>> & Partial<MutateProps<{}, {}>>, any>'.
Types of parameters 'props' and 'props' are incompatible.
Type 'Partial<DataProps<{}, {}>> & Partial<MutateProps<{}, {}>>' is not assignable to type 'Props'.
Types of property 'data' are incompatible.
Type 'DataValue<{}, {}> | undefined' is not assignable to type 'Security'.
Type 'undefined' is not assignable to type 'Security'. [2345]
class ProductChecker
答案 0 :(得分:0)
再试一次:
import { graphql, ChildDataProps } from 'react-apollo'
type TSecurity = {
loading: Boolean;
}
type TProps = {
data: TSecurity
}
// ChildDataProps<InputProps, Response, Variables>
type TChildProps = ChildDataProps<{}, TProps , {}>
// graphql<InputProps, Response, Variables, ChildProps>()
graphql<{}, TProps, {}, TChildProps>(getSymbolInfoQuery)(ProductChecker)
有关将Apollo与TypeScript结合使用的更多信息,是here
答案 1 :(得分:-4)
displaySearchFilters() { console.log(this.props); }
这应该在渲染上方