FormidableLabs / groqd

A schema-unaware, runtime and type-safe query builder for GROQ.
https://commerce.nearform.com/open-source/groqd
MIT License
230 stars 16 forks source link

Typing to use when passing q to function #218

Closed Michael-1 closed 11 months ago

Michael-1 commented 1 year ago

I would like to structure my code such that I define a query with the frontend component that is using the query’s result, and to have a library function that takes care of handling the fetching, caching and all the usual. Yet I’m having issues with correctly typing the input and output for the library function.

// UIComponent.tsx
…
const {data, isLoading} = useContent(
  q('*').filter(…).grab(…),
  {language: 'en'}
)
…
// useContent.ts
…

export default (
  query: WhatTypeToUseHere,
  parameters?: Record<string, unknown>
) => {
  const {
    state: {previewMode},
  } = useStore()

  const parsedQuery = query.query
  type ReturnType = InferType<typeof query>

  if (previewMode)
    return …

  return useSWRImmutable<ReturnType>([parsedQuery, parameters], () =>
    sanity<ReturnType>(parsedQuery, parameters)
  )
}

What would I use for WhatTypeToUseHere? Or how could I achieve what I want, with correct typings?

Michael-1 commented 11 months ago

I found a solution with generics:

export default <Query extends {query: string}>  (
  query: Query,
  parameters?: Record<string, unknown>
) => {
  type ReturnType = InferType<Query>

Though I would prefer if GROQD would export its internal types, like BaseQuery