在Apollo Client中,使用Typescript时,我们可以通过定义返回类型来指定GraphQL查询的返回值类型。下面是一个示例解决方案:
首先,安装必需的依赖项:
npm install apollo-boost graphql
npm install @apollo/react-hooks
npm install @types/react @types/react-dom @types/react-router-dom
然后,创建一个Apollo Client实例并导出它:
import ApolloClient from 'apollo-boost';
const client = new ApolloClient({
uri: 'http://localhost:4000/graphql',
});
export default client;
接下来,创建一个GraphQL查询并定义返回类型:
import { gql } from 'apollo-boost';
export const GET_USER = gql`
query GetUser($id: ID!) {
user(id: $id) {
id
name
email
}
}
`;
export interface User {
id: string;
name: string;
email: string;
}
在这个示例中,我们定义了一个名为GET_USER
的查询,它接受一个id
参数,并期望返回一个User
对象。
最后,使用Apollo Client和定义的查询来获取数据:
import React from 'react';
import { useQuery } from '@apollo/react-hooks';
import { GET_USER, User } from './queries';
const UserProfile: React.FC<{ id: string }> = ({ id }) => {
const { data, loading, error } = useQuery<{ user: User }, { id: string }>(GET_USER, {
variables: { id },
});
if (loading) {
return Loading...;
}
if (error) {
return Error: {error.message};
}
return (
{data?.user.name}
Email: {data?.user.email}
);
};
export default UserProfile;
在这个示例中,我们使用useQuery
钩子来执行GET_USER
查询,并将返回的数据类型定义为{ user: User }
。我们还将查询的id
参数的类型定义为{ id: string }
。
这是一个基本的示例,你可以根据自己的需求进行修改和扩展。