|
1 | 1 | --- |
2 | | -description: 强制使用 TypeScript 确保 GraphQL 操作的类型安全。 |
| 2 | +description: "强制使用 TypeScript 确保 GraphQL 操作的类型安全" |
3 | 3 | globs: src/graphql/**/*.ts |
4 | 4 | --- |
5 | | -- 对 GraphQL 操作使用 TypeScript 确保类型安全 |
| 5 | +- **对 GraphQL 操作使用 TypeScript 确保类型安全**: |
| 6 | + - **代码生成**:利用 GraphQL Code Generator 或类似工具,根据 GraphQL schema 和操作(Queries, Mutations, Subscriptions)自动生成 TypeScript 类型定义。 |
| 7 | + - **类型推断**:确保 `useQuery`、`useMutation` 和 `useSubscription` Hooks 的返回值(`data`, `loading`, `error`)和变量(`variables`)都具有正确的类型推断。 |
| 8 | + - **端到端类型安全**:从 GraphQL API 到前端组件,实现端到端的类型安全,减少运行时错误。 |
| 9 | + - **示例**: |
| 10 | + ```typescript |
| 11 | + // graphql.schema.json (部分) |
| 12 | + { |
| 13 | + "data": { |
| 14 | + "__schema": { |
| 15 | + "types": [ |
| 16 | + { |
| 17 | + "kind": "OBJECT", |
| 18 | + "name": "User", |
| 19 | + "fields": [ |
| 20 | + { "name": "id", "type": { "kind": "NON_NULL", "ofType": { "kind": "SCALAR", "name": "ID" } } }, |
| 21 | + { "name": "name", "type": { "kind": "SCALAR", "name": "String" } } |
| 22 | + ] |
| 23 | + } |
| 24 | + ] |
| 25 | + } |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + // query.graphql |
| 30 | + query GetUser($id: ID!) { |
| 31 | + user(id: $id) { |
| 32 | + id |
| 33 | + name |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + // generated.ts (通过工具生成) |
| 38 | + export type GetUserQueryVariables = { |
| 39 | + id: string; |
| 40 | + }; |
| 41 | + |
| 42 | + export type GetUserQuery = { |
| 43 | + user?: { |
| 44 | + __typename?: "User"; |
| 45 | + id: string; |
| 46 | + name?: string | null; |
| 47 | + } | null; |
| 48 | + }; |
| 49 | + |
| 50 | + // component.tsx |
| 51 | + import { useQuery } from '@apollo/client'; |
| 52 | + import { GetUserQuery, GetUserQueryVariables } from './generated'; // 假设类型已生成 |
| 53 | + |
| 54 | + const GET_USER_QUERY = gql` |
| 55 | + query GetUser($id: ID!) { |
| 56 | + user(id: $id) { |
| 57 | + id |
| 58 | + name |
| 59 | + } |
| 60 | + } |
| 61 | + `; |
| 62 | + |
| 63 | + function UserProfile({ userId }: { userId: string }) { |
| 64 | + const { data, loading, error } = useQuery<GetUserQuery, GetUserQueryVariables>(GET_USER_QUERY, { |
| 65 | + variables: { id: userId }, |
| 66 | + }); |
| 67 | + |
| 68 | + if (loading) return <p>Loading...</p>; |
| 69 | + if (error) return <p>Error: {error.message}</p>; |
| 70 | + |
| 71 | + return ( |
| 72 | + <div> |
| 73 | + <h1>{data?.user?.name}</h1> |
| 74 | + <p>ID: {data?.user?.id}</p> |
| 75 | + </div> |
| 76 | + ); |
| 77 | + } |
| 78 | + ``` |
| 79 | + - **手动类型定义(不推荐)**:在无法使用代码生成工具的情况下,可以手动定义 GraphQL 响应的 TypeScript 接口,但这容易出错且难以维护。 |
0 commit comments