Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

narrow return value of useFragment based on returnPartialData option #10760

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/nine-clouds-watch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@apollo/client': patch
---

narrow return value of `useFragment` based on `returnPartialData` option
35 changes: 35 additions & 0 deletions src/react/hooks/__tests__/useFragment.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1301,4 +1301,39 @@ describe.skip("Type Tests", () => {
}
});
})

test("`returnPartialData: false` results in `TData`, otherwise `Partial<TData>`", () => {
const typedNode = {} as TypedDocumentNode<{ foo: string}>
{
// default: return type is `Partial<TData>`
const result = useFragment({
fragment: typedNode,
from: { __typename: "Query" }
})
const test1: Partial<{ foo: string }> | undefined = result.data
// @ts-expect-error
const test2: { foo: string } | undefined = result.data
}
{
// `returnPartialData: true`: return type is `Partial<TData>`
const result = useFragment({
fragment: typedNode,
from: { __typename: "Query" },
returnPartialData: true
})
const test1: Partial<{ foo: string }> | undefined = result.data
// @ts-expect-error
const test2: { foo: string } | undefined = result.data
}
{
// `returnPartialData: false`: return type is `TData`
const result = useFragment({
fragment: typedNode,
from: { __typename: "Query" },
returnPartialData: false
})
const test1: Partial<{ foo: string }> | undefined = result.data
const test2: { foo: string } | undefined = result.data
}
})
})
13 changes: 12 additions & 1 deletion src/react/hooks/useFragment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,18 @@ export interface UseFragmentResult<TData> {
complete: boolean;
missing?: MissingTree;
}

export function useFragment_experimental<
TData = any,
TVars = OperationVariables
>(
options: UseFragmentOptions<TData, TVars> & { returnPartialData: false },
): UseFragmentResult<TData>
export function useFragment_experimental<
TData = any,
TVars = OperationVariables
>(
options: UseFragmentOptions<TData, TVars>,
): UseFragmentResult<Partial<TData>>
export function useFragment_experimental<
TData = any,
TVars = OperationVariables
Expand Down