Repository: apollographql/apollo-client

Problem statement:
Ensure more accurate `TData` TypeScript types for `useSuspenseQuery`
Currently `useSuspenseQuery` sets the returned `data` property to type `TData` (a generic). This works well with the default behavior since the hook will throw errors when encountered.

There are however a couple cases that will cause `data` to remain `undefined`.

1. Setting `errorPolicy` to anything other than `none` (the default). If an error is encountered with `all` or `ignore`, the error is not thrown and is expected to be handled locally, but `data` might not be set.
2. Setting `skip` to `true` (#10532). Once this is supported, `skip` will not load any data, so `data` is expected to be `undefined` until `skip` is `false`.

Additionally, setting `returnPartialData` may result in some of missing data. In this case, we should set `data` to `DeepPartial<TData>` (note `DeepPartial` is not a part of TypeScript: we'll need a helper) to better communicate that the `data` type might not contain all the required values.

In short, our types should reflect the following:
* `errorPolicy: 'none'` -> `data: TData`
* `errorPolicy: 'ignore'` -> `data: TData | undefined`
* `errorPolicy: 'all'` -> `data: TData | undefined`
* `skip: false` -> `data: TData`
* `skip: true` -> `data: TData | undefined`
* `returnPartialData: true` -> `data: DeepPartial<TData>`
* `returnPartialData: false` -> `data: TData`



Hints:

Patch:
diff --git a/src/react/hooks/useSuspenseQuery.ts b/src/react/hooks/useSuspenseQuery.ts
--- a/src/react/hooks/useSuspenseQuery.ts
+++ b/src/react/hooks/useSuspenseQuery.ts
@@ -13,13 +13,14 @@ import {
   NetworkStatus,
   FetchMoreQueryOptions,
 } from '../../core';
-import { isNonEmptyArray } from '../../utilities';
+import { DeepPartial, isNonEmptyArray } from '../../utilities';
 import { useApolloClient } from './useApolloClient';
 import { DocumentType, verifyDocumentType } from '../parser';
 import {
   SuspenseQueryHookFetchPolicy,
   SuspenseQueryHookOptions,
   ObservableQueryFields,
+  NoInfer,
 } from '../types/types';
 import { useDeepMemo, useStrictModeSafeCleanupEffect, __use } from './internal';
 import { useSuspenseCache } from './useSuspenseCache';
@@ -28,7 +29,7 @@ import { QuerySubscription } from '../cache/QuerySubscription';
 import { canonicalStringify } from '../../cache';
 
 export interface UseSuspenseQueryResult<
-  TData = any,
+  TData = unknown,
   TVariables extends OperationVariables = OperationVariables
 > {
   client: ApolloClient<any>;
@@ -63,11 +64,72 @@ type SubscribeToMoreFunction<
 > = ObservableQueryFields<TData, TVariables>['subscribeToMore'];
 
 export function useSuspenseQuery_experimental<
-  TData = any,
+  TData,
+  TVariables extends OperationVariables,
+  TOptions extends Omit<SuspenseQueryHookOptions<TData>, 'variables'>
+>(
+  query: DocumentNode | TypedDocumentNode<TData, TVariables>,
+  options?: SuspenseQueryHookOptions<NoInfer<TData>, NoInfer<TVariables>> &
+    TOptions
+): UseSuspenseQueryResult<
+  TOptions['errorPolicy'] extends 'ignore' | 'all'
+    ? TOptions['returnPartialData'] extends true
+      ? DeepPartial<TData> | undefined
+      : TData | undefined
+    : TOptions['returnPartialData'] extends true
+    ? DeepPartial<TData>
+    : TData,
+  TVariables
+>;
+
+export function useSuspenseQuery_experimental<
+  TData = unknown,
+  TVariables extends OperationVariables = OperationVariables
+>(
+  query: DocumentNode | TypedDocumentNode<TData, TVariables>,
+  options: SuspenseQueryHookOptions<NoInfer<TData>, NoInfer<TVariables>> & {
+    returnPartialData: true;
+    errorPolicy: 'ignore' | 'all';
+  }
+): UseSuspenseQueryResult<DeepPartial<TData> | undefined, TVariables>;
+
+export function useSuspenseQuery_experimental<
+  TData = unknown,
+  TVariables extends OperationVariables = OperationVariables
+>(
+  query: DocumentNode | TypedDocumentNode<TData, TVariables>,
+  options: SuspenseQueryHookOptions<NoInfer<TData>, NoInfer<TVariables>> & {
+    errorPolicy: 'ignore' | 'all';
+  }
+): UseSuspenseQueryResult<TData | undefined, TVariables>;
+
+export function useSuspenseQuery_experimental<
+  TData = unknown,
+  TVariables extends OperationVariables = OperationVariables
+>(
+  query: DocumentNode | TypedDocumentNode<TData, TVariables>,
+  options: SuspenseQueryHookOptions<NoInfer<TData>, NoInfer<TVariables>> & {
+    returnPartialData: true;
+  }
+): UseSuspenseQueryResult<DeepPartial<TData>, TVariables>;
+
+export function useSuspenseQuery_experimental<
+  TData = unknown,
+  TVariables extends OperationVariables = OperationVariables
+>(
+  query: DocumentNode | TypedDocumentNode<TData, TVariables>,
+  options?: SuspenseQueryHookOptions<NoInfer<TData>, NoInfer<TVariables>>
+): UseSuspenseQueryResult<TData, TVariables>;
+
+export function useSuspenseQuery_experimental<
+  TData = unknown,
   TVariables extends OperationVariables = OperationVariables
 >(
   query: DocumentNode | TypedDocumentNode<TData, TVariables>,
-  options: SuspenseQueryHookOptions<TData, TVariables> = Object.create(null)
+  options: SuspenseQueryHookOptions<
+    NoInfer<TData>,
+    NoInfer<TVariables>
+  > = Object.create(null)
 ): UseSuspenseQueryResult<TData, TVariables> {
   const didPreviouslySuspend = useRef(false);
   const client = useApolloClient(options.client);
diff --git a/src/react/types/types.ts b/src/react/types/types.ts
--- a/src/react/types/types.ts
+++ b/src/react/types/types.ts
@@ -118,7 +118,7 @@ export type SuspenseQueryHookFetchPolicy = Extract<
 >;
 
 export interface SuspenseQueryHookOptions<
-  TData = any,
+  TData = unknown,
   TVariables extends OperationVariables = OperationVariables
 > extends Pick<
   QueryHookOptions<TData, TVariables>,
diff --git a/src/utilities/index.ts b/src/utilities/index.ts
--- a/src/utilities/index.ts
+++ b/src/utilities/index.ts
@@ -109,3 +109,4 @@ export { stripTypename } from './common/stripTypename';
 
 export * from './types/IsStrictlyAny';
 export { DeepOmit } from './types/DeepOmit';
+export { DeepPartial } from './types/DeepPartial';
diff --git a/src/utilities/types/DeepOmit.ts b/src/utilities/types/DeepOmit.ts
--- a/src/utilities/types/DeepOmit.ts
+++ b/src/utilities/types/DeepOmit.ts
@@ -1,12 +1,7 @@
-// DeepOmit primitives include functions and symbols since these are unmodified.
-type Primitive =
-  | string
-  | Function
-  | number
-  | boolean
-  | Symbol
-  | undefined
-  | null;
+import { Primitive } from './Primitive';
+
+// DeepOmit primitives include functions since these are unmodified.
+type DeepOmitPrimitive = Primitive | Function;
 
 export type DeepOmitArray<T extends any[], K> = {
   [P in keyof T]: DeepOmit<T[P], K>;
@@ -24,11 +19,11 @@ export type DeepOmitArray<T extends any[], K> = {
 // This should be fine as of the time of this writing until omitDeep gets
 // broader use since this utility is only used to strip __typename from
 // `variables`; a case in which class instances are invalid anyways.
-export type DeepOmit<T, K> = T extends Primitive
+export type DeepOmit<T, K> = T extends DeepOmitPrimitive
   ? T
   : {
       [P in Exclude<keyof T, K>]: T[P] extends infer TP
-        ? TP extends Primitive
+        ? TP extends DeepOmitPrimitive
           ? TP
           : TP extends any[]
           ? DeepOmitArray<TP, K>
diff --git a/src/utilities/types/DeepPartial.ts b/src/utilities/types/DeepPartial.ts
new file mode 100644
--- /dev/null
+++ b/src/utilities/types/DeepPartial.ts
@@ -0,0 +1,58 @@
+// Inspired by type-fest PartialDeep: https://github.com/sindresorhus/type-fest/blob/9feb8c89be9a0f2f688bf2f497230298a8e2472e/source/partial-deep.d.ts
+//
+// We're including the license to give credit to the original implementation.
+// https://github.com/sindresorhus/type-fest/blob/main/license-mit
+
+/*
+ * MIT License
+ *
+ * Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+import { Primitive } from './Primitive';
+
+type DeepPartialPrimitive = Primitive | Date | RegExp;
+
+export type DeepPartial<T> = T extends DeepPartialPrimitive
+  ? T
+  : T extends Map<infer TKey, infer TValue>
+  ? DeepPartialMap<TKey, TValue>
+  : T extends ReadonlyMap<infer TKey, infer TValue>
+  ? DeepPartialReadonlyMap<TKey, TValue>
+  : T extends Set<infer TItem>
+  ? DeepPartialSet<TItem>
+  : T extends ReadonlySet<infer TItem>
+  ? DeepPartialReadonlySet<TItem>
+  : T extends (...args: any[]) => unknown
+  ? T | undefined
+  : T extends object
+  ? T extends ReadonlyArray<infer TItem> // Test for arrays/tuples
+    ? TItem[] extends T // Test for non-tuples
+      ? readonly TItem[] extends T
+        ? ReadonlyArray<DeepPartial<TItem | undefined>>
+        : Array<DeepPartial<TItem | undefined>>
+      : DeepPartialObject<T>
+    : DeepPartialObject<T>
+  : unknown;
+
+type DeepPartialMap<TKey, TValue> = {} & Map<
+  DeepPartial<TKey>,
+  DeepPartial<TValue>
+>;
+
+type DeepPartialReadonlyMap<TKey, TValue> = {} & ReadonlyMap<
+  DeepPartial<TKey>,
+  DeepPartial<TValue>
+>;
+
+type DeepPartialSet<T> = {} & Set<DeepPartial<T>>;
+type DeepPartialReadonlySet<T> = {} & ReadonlySet<DeepPartial<T>>;
+
+type DeepPartialObject<T extends object> = {
+  [K in keyof T]?: DeepPartial<T[K]>;
+};
diff --git a/src/utilities/types/Primitive.ts b/src/utilities/types/Primitive.ts
new file mode 100644
--- /dev/null
+++ b/src/utilities/types/Primitive.ts
@@ -0,0 +1,9 @@
+// Matches any primitive value: https://developer.mozilla.org/en-US/docs/Glossary/Primitive.
+export type Primitive =
+  | null
+  | undefined
+  | string
+  | number
+  | boolean
+  | symbol
+  | bigint;


Test patch:
diff --git a/src/react/hooks/__tests__/useSuspenseQuery.test.tsx b/src/react/hooks/__tests__/useSuspenseQuery.test.tsx
--- a/src/react/hooks/__tests__/useSuspenseQuery.test.tsx
+++ b/src/react/hooks/__tests__/useSuspenseQuery.test.tsx
@@ -13,6 +13,7 @@ import { ErrorBoundary } from 'react-error-boundary';
 import { GraphQLError } from 'graphql';
 import { InvariantError } from 'ts-invariant';
 import { equal } from '@wry/equality';
+import { expectTypeOf } from 'expect-type';
 
 import {
   gql,
@@ -30,6 +31,7 @@ import {
   NetworkStatus,
 } from '../../../core';
 import {
+  DeepPartial,
   compact,
   concatPagination,
   getMainDefinition,
@@ -234,21 +236,24 @@ function useErrorCase<TData extends ErrorCaseData>(
   return { query, mocks: [mock] };
 }
 
-function useVariablesQueryCase() {
-  const CHARACTERS = ['Spider-Man', 'Black Widow', 'Iron Man', 'Hulk'];
+interface VariablesCaseData {
+  character: {
+    id: string;
+    name: string;
+  };
+}
 
-  interface QueryData {
-    character: {
-      id: string;
-      name: string;
-    };
-  }
+interface VariablesCaseVariables {
+  id: string;
+}
 
-  interface QueryVariables {
-    id: string;
-  }
+function useVariablesQueryCase() {
+  const CHARACTERS = ['Spider-Man', 'Black Widow', 'Iron Man', 'Hulk'];
 
-  const query: TypedDocumentNode<QueryData, QueryVariables> = gql`
+  const query: TypedDocumentNode<
+    VariablesCaseData,
+    VariablesCaseVariables
+  > = gql`
     query CharacterQuery($id: ID!) {
       character(id: $id) {
         id
@@ -3129,7 +3134,7 @@ describe('useSuspenseQuery', () => {
   });
 
   it('can unset a globally defined variable', async () => {
-    const query = gql`
+    const query: TypedDocumentNode<{ vars: Record<string, any> }> = gql`
       query MergedVariablesQuery {
         vars
       }
@@ -7008,4 +7013,251 @@ describe('useSuspenseQuery', () => {
       expect(todo).toHaveTextContent('Take out trash (completed)');
     });
   });
+
+  describe.skip('type tests', () => {
+    it('returns unknown when TData cannot be inferred', () => {
+      const query = gql`
+        query {
+          hello
+        }
+      `;
+
+      const { data } = useSuspenseQuery(query);
+
+      expectTypeOf(data).toEqualTypeOf<unknown>();
+    });
+
+    it('disallows wider variables type than specified', () => {
+      const { query } = useVariablesQueryCase();
+
+      // @ts-expect-error should not allow wider TVariables type
+      useSuspenseQuery(query, { variables: { id: '1', foo: 'bar' } });
+    });
+
+    it('returns TData in default case', () => {
+      const { query } = useVariablesQueryCase();
+
+      const { data: inferred } = useSuspenseQuery(query);
+
+      expectTypeOf(inferred).toEqualTypeOf<VariablesCaseData>();
+      expectTypeOf(inferred).not.toEqualTypeOf<VariablesCaseData | undefined>();
+
+      const { data: explicit } = useSuspenseQuery<
+        VariablesCaseData,
+        VariablesCaseVariables
+      >(query);
+
+      expectTypeOf(explicit).toEqualTypeOf<VariablesCaseData>();
+      expectTypeOf(explicit).not.toEqualTypeOf<VariablesCaseData | undefined>();
+    });
+
+    it('returns TData | undefined with errorPolicy: "ignore"', () => {
+      const { query } = useVariablesQueryCase();
+
+      const { data: inferred } = useSuspenseQuery(query, {
+        errorPolicy: 'ignore',
+      });
+
+      expectTypeOf(inferred).toEqualTypeOf<VariablesCaseData | undefined>();
+      expectTypeOf(inferred).not.toEqualTypeOf<VariablesCaseData>();
+
+      const { data: explicit } = useSuspenseQuery<
+        VariablesCaseData,
+        VariablesCaseVariables
+      >(query, { errorPolicy: 'ignore' });
+
+      expectTypeOf(explicit).toEqualTypeOf<VariablesCaseData | undefined>();
+      expectTypeOf(explicit).not.toEqualTypeOf<VariablesCaseData>();
+    });
+
+    it('returns TData | undefined with errorPolicy: "all"', () => {
+      const { query } = useVariablesQueryCase();
+
+      const { data: inferred } = useSuspenseQuery(query, {
+        errorPolicy: 'all',
+      });
+
+      expectTypeOf(inferred).toEqualTypeOf<VariablesCaseData | undefined>();
+      expectTypeOf(inferred).not.toEqualTypeOf<VariablesCaseData>();
+
+      const { data: explicit } = useSuspenseQuery<
+        VariablesCaseData,
+        VariablesCaseVariables
+      >(query, {
+        errorPolicy: 'all',
+      });
+
+      expectTypeOf(explicit).toEqualTypeOf<VariablesCaseData | undefined>();
+      expectTypeOf(explicit).not.toEqualTypeOf<VariablesCaseData>();
+    });
+
+    it('returns TData with errorPolicy: "none"', () => {
+      const { query } = useVariablesQueryCase();
+
+      const { data: inferred } = useSuspenseQuery(query, {
+        errorPolicy: 'none',
+      });
+
+      expectTypeOf(inferred).toEqualTypeOf<VariablesCaseData>();
+      expectTypeOf(inferred).not.toEqualTypeOf<VariablesCaseData | undefined>();
+
+      const { data: explicit } = useSuspenseQuery<
+        VariablesCaseData,
+        VariablesCaseVariables
+      >(query, { errorPolicy: 'none' });
+
+      expectTypeOf(explicit).toEqualTypeOf<VariablesCaseData>();
+      expectTypeOf(explicit).not.toEqualTypeOf<VariablesCaseData | undefined>();
+    });
+
+    it('returns DeepPartial<TData> with returnPartialData: true', () => {
+      const { query } = useVariablesQueryCase();
+
+      const { data: inferred } = useSuspenseQuery(query, {
+        returnPartialData: true,
+      });
+
+      expectTypeOf(inferred).toEqualTypeOf<DeepPartial<VariablesCaseData>>();
+      expectTypeOf(inferred).not.toEqualTypeOf<VariablesCaseData>();
+
+      const { data: explicit } = useSuspenseQuery<
+        VariablesCaseData,
+        VariablesCaseVariables
+      >(query, { returnPartialData: true });
+
+      expectTypeOf(explicit).toEqualTypeOf<DeepPartial<VariablesCaseData>>();
+      expectTypeOf(explicit).not.toEqualTypeOf<VariablesCaseData>();
+    });
+
+    it('returns TData with returnPartialData: false', () => {
+      const { query } = useVariablesQueryCase();
+
+      const { data: inferred } = useSuspenseQuery(query, {
+        returnPartialData: false,
+      });
+
+      expectTypeOf(inferred).toEqualTypeOf<VariablesCaseData>();
+      expectTypeOf(inferred).not.toEqualTypeOf<
+        DeepPartial<VariablesCaseData>
+      >();
+
+      const { data: explicit } = useSuspenseQuery<
+        VariablesCaseData,
+        VariablesCaseVariables
+      >(query, {
+        returnPartialData: false,
+      });
+
+      expectTypeOf(explicit).toEqualTypeOf<VariablesCaseData>();
+      expectTypeOf(explicit).not.toEqualTypeOf<
+        DeepPartial<VariablesCaseData>
+      >();
+    });
+
+    it('returns TData when passing an option that does not affect TData', () => {
+      const { query } = useVariablesQueryCase();
+
+      const { data: inferred } = useSuspenseQuery(query, {
+        fetchPolicy: 'no-cache',
+      });
+
+      expectTypeOf(inferred).toEqualTypeOf<VariablesCaseData>();
+      expectTypeOf(inferred).not.toEqualTypeOf<
+        DeepPartial<VariablesCaseData>
+      >();
+
+      const { data: explicit } = useSuspenseQuery<
+        VariablesCaseData,
+        VariablesCaseVariables
+      >(query, { fetchPolicy: 'no-cache' });
+
+      expectTypeOf(explicit).toEqualTypeOf<VariablesCaseData>();
+      expectTypeOf(explicit).not.toEqualTypeOf<
+        DeepPartial<VariablesCaseData>
+      >();
+    });
+
+    it('handles combinations of options', () => {
+      const { query } = useVariablesQueryCase();
+
+      const { data: inferredPartialDataIgnore } = useSuspenseQuery(query, {
+        returnPartialData: true,
+        errorPolicy: 'ignore',
+      });
+
+      expectTypeOf(inferredPartialDataIgnore).toEqualTypeOf<
+        DeepPartial<VariablesCaseData> | undefined
+      >();
+      expectTypeOf(
+        inferredPartialDataIgnore
+      ).not.toEqualTypeOf<VariablesCaseData>();
+
+      const { data: explicitPartialDataIgnore } = useSuspenseQuery<
+        VariablesCaseData,
+        VariablesCaseVariables
+      >(query, {
+        returnPartialData: true,
+        errorPolicy: 'ignore',
+      });
+
+      expectTypeOf(explicitPartialDataIgnore).toEqualTypeOf<
+        DeepPartial<VariablesCaseData> | undefined
+      >();
+      expectTypeOf(
+        explicitPartialDataIgnore
+      ).not.toEqualTypeOf<VariablesCaseData>();
+
+      const { data: inferredPartialDataNone } = useSuspenseQuery(query, {
+        returnPartialData: true,
+        errorPolicy: 'none',
+      });
+
+      expectTypeOf(inferredPartialDataNone).toEqualTypeOf<
+        DeepPartial<VariablesCaseData>
+      >();
+      expectTypeOf(
+        inferredPartialDataNone
+      ).not.toEqualTypeOf<VariablesCaseData>();
+
+      const { data: explicitPartialDataNone } = useSuspenseQuery<
+        VariablesCaseData,
+        VariablesCaseVariables
+      >(query, {
+        returnPartialData: true,
+        errorPolicy: 'none',
+      });
+
+      expectTypeOf(explicitPartialDataNone).toEqualTypeOf<
+        DeepPartial<VariablesCaseData>
+      >();
+      expectTypeOf(
+        explicitPartialDataNone
+      ).not.toEqualTypeOf<VariablesCaseData>();
+    });
+
+    it('returns correct TData type when combined options that do not affect TData', () => {
+      const { query } = useVariablesQueryCase();
+
+      const { data: inferred } = useSuspenseQuery(query, {
+        fetchPolicy: 'no-cache',
+        returnPartialData: true,
+        errorPolicy: 'none',
+      });
+
+      expectTypeOf(inferred).toEqualTypeOf<DeepPartial<VariablesCaseData>>();
+      expectTypeOf(inferred).not.toEqualTypeOf<VariablesCaseData>();
+
+      const { data: explicit } = useSuspenseQuery<
+        VariablesCaseData,
+        VariablesCaseVariables
+      >(query, {
+        fetchPolicy: 'no-cache',
+        returnPartialData: true,
+        errorPolicy: 'none',
+      });
+
+      expectTypeOf(explicit).toEqualTypeOf<DeepPartial<VariablesCaseData>>();
+      expectTypeOf(explicit).not.toEqualTypeOf<VariablesCaseData>();
+    });
+  });
 });