Skip to content

Commit 3a16867

Browse files
authored
fix(types): initialData function that returns undefined should still discriminate after isSuccess check (#5869)
1 parent 047005e commit 3a16867

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

packages/react-query/src/__tests__/useQuery.types.test.tsx

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,26 @@ describe('initialData', () => {
111111
return result
112112
})
113113
})
114+
115+
it('TData should be narrowed after an isSuccess check when initialData is provided as a function which can return undefined', () => {
116+
doNotExecute(() => {
117+
const { data, isSuccess } = useQuery({
118+
queryKey: ['key'],
119+
queryFn: () => {
120+
return {
121+
wow: true,
122+
}
123+
},
124+
initialData: () => undefined as { wow: boolean } | undefined,
125+
})
126+
127+
if (isSuccess) {
128+
const result: Expect<Equal<{ wow: boolean }, typeof data>> = true
129+
return result
130+
}
131+
return false
132+
})
133+
})
114134
})
115135

116136
describe('custom hook', () => {

packages/react-query/src/queryOptions.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,17 @@ export type UndefinedInitialDataOptions<
1010
initialData?: undefined
1111
}
1212

13+
type NonUndefinedGuard<T> = T extends undefined ? never : T
14+
1315
export type DefinedInitialDataOptions<
1416
TQueryFnData = unknown,
1517
TError = DefaultError,
1618
TData = TQueryFnData,
1719
TQueryKey extends QueryKey = QueryKey,
1820
> = UseQueryOptions<TQueryFnData, TError, TData, TQueryKey> & {
19-
initialData: TQueryFnData | (() => TQueryFnData)
21+
initialData:
22+
| NonUndefinedGuard<TQueryFnData>
23+
| (() => NonUndefinedGuard<TQueryFnData>)
2024
}
2125

2226
export function queryOptions<

0 commit comments

Comments
 (0)