Skip to content

Commit 3f057a2

Browse files
authored
feat(types): validate queryOptions (#5991)
* feat: validate queryOptions * chore: "disable" test because of upstream issue
1 parent 1833366 commit 3f057a2

File tree

2 files changed

+37
-2
lines changed

2 files changed

+37
-2
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import { queryOptions } from '../queryOptions'
2+
import { doNotExecute } from './utils'
3+
import type { Equal, Expect } from './utils'
4+
5+
describe('queryOptions', () => {
6+
it('should not allow excess properties', () => {
7+
doNotExecute(() => {
8+
// @ts-expect-error this is a good error, because stallTime does not exist!
9+
return queryOptions({
10+
queryKey: ['key'],
11+
queryFn: () => Promise.resolve(5),
12+
stallTime: 1000,
13+
})
14+
})
15+
})
16+
it('should infer types for callbacks', () => {
17+
doNotExecute(() => {
18+
return queryOptions({
19+
queryKey: ['key'],
20+
queryFn: () => Promise.resolve(5),
21+
staleTime: 1000,
22+
select: (data) => {
23+
// @ts-expect-error data is in fact inferred as unknown
24+
// see https://github.com/microsoft/TypeScript/issues/47599
25+
const result: Expect<Equal<number, typeof data>> = true
26+
return result
27+
},
28+
})
29+
})
30+
})
31+
})

packages/react-query/src/queryOptions.ts

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,10 @@ export type DefinedInitialDataOptions<
2323
| (() => NonUndefinedGuard<TQueryFnData>)
2424
}
2525

26+
type ValidateQueryOptions<T> = {
27+
[K in keyof T]: K extends keyof UseQueryOptions ? T[K] : never
28+
}
29+
2630
export function queryOptions<
2731
TQueryFnData = unknown,
2832
TError = DefaultError,
@@ -34,7 +38,7 @@ export function queryOptions<
3438
TData,
3539
TQueryKey
3640
> = UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>,
37-
>(options: TOptions): TOptions
41+
>(options: ValidateQueryOptions<TOptions>): TOptions
3842

3943
export function queryOptions<
4044
TQueryFnData = unknown,
@@ -47,7 +51,7 @@ export function queryOptions<
4751
TData,
4852
TQueryKey
4953
> = DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>,
50-
>(options: TOptions): TOptions
54+
>(options: ValidateQueryOptions<TOptions>): TOptions
5155

5256
export function queryOptions(options: unknown) {
5357
return options

0 commit comments

Comments
 (0)