Skip to content

Commit

Permalink
feat(types): validate queryOptions (#5991)
Browse files Browse the repository at this point in the history
* feat: validate queryOptions

* chore: "disable" test because of upstream issue
  • Loading branch information
TkDodo committed Sep 12, 2023
1 parent 1833366 commit 3f057a2
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
31 changes: 31 additions & 0 deletions packages/react-query/src/__tests__/queryOptions.types.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { queryOptions } from '../queryOptions'
import { doNotExecute } from './utils'
import type { Equal, Expect } from './utils'

describe('queryOptions', () => {
it('should not allow excess properties', () => {
doNotExecute(() => {
// @ts-expect-error this is a good error, because stallTime does not exist!
return queryOptions({
queryKey: ['key'],
queryFn: () => Promise.resolve(5),
stallTime: 1000,
})
})
})
it('should infer types for callbacks', () => {
doNotExecute(() => {
return queryOptions({
queryKey: ['key'],
queryFn: () => Promise.resolve(5),
staleTime: 1000,
select: (data) => {
// @ts-expect-error data is in fact inferred as unknown
// see https://github.com/microsoft/TypeScript/issues/47599
const result: Expect<Equal<number, typeof data>> = true
return result
},
})
})
})
})
8 changes: 6 additions & 2 deletions packages/react-query/src/queryOptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ export type DefinedInitialDataOptions<
| (() => NonUndefinedGuard<TQueryFnData>)
}

type ValidateQueryOptions<T> = {
[K in keyof T]: K extends keyof UseQueryOptions ? T[K] : never
}

export function queryOptions<
TQueryFnData = unknown,
TError = DefaultError,
Expand All @@ -34,7 +38,7 @@ export function queryOptions<
TData,
TQueryKey
> = UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>,
>(options: TOptions): TOptions
>(options: ValidateQueryOptions<TOptions>): TOptions

export function queryOptions<
TQueryFnData = unknown,
Expand All @@ -47,7 +51,7 @@ export function queryOptions<
TData,
TQueryKey
> = DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>,
>(options: TOptions): TOptions
>(options: ValidateQueryOptions<TOptions>): TOptions

export function queryOptions(options: unknown) {
return options
Expand Down

0 comments on commit 3f057a2

Please sign in to comment.