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

help: How would I use the typescript type for defining props for example? #598

Open
felixmpaulus opened this issue Jan 20, 2024 · 0 comments
Assignees

Comments

@felixmpaulus
Copy link

felixmpaulus commented Jan 20, 2024

📚 What are you trying to do? Please describe.
I want to define the type for my getStaticProps function that is making queries to sanity.

🔍 What have you tried?
Using the type returned by queryBuilder.use() at the top of my file to retrieve the type. But it feels wrong. Like this:

import { queryBuilder as someQueryBuilder } from '/path/to/schema/file'
const [_, someType] = someQueryBuilder.use()

type Props = {
  some: typeof someType
}

ℹ️ Additional context
This is what I am building on top of. I have no idea how to type my props.

import { readToken } from 'lib/sanity.api'
import {
  getAllCities,
} from 'lib/sanity.client'
import { GetStaticProps } from 'next'
import type { SharedPageProps } from 'pages/_app'

interface PageProps extends SharedPageProps {
  cities: // <---- I need the type returned by the query here...
}

export default function Page(props: PageProps) {
  const { cities } = props
  return (
    ...
  )
}

interface Query {
  [key: string]: string
}

export const getStaticProps: GetStaticProps<PageProps, Query> = async (ctx) => {
  const { draftMode = false } = ctx
  const client = getClient(draftMode ? { token: readToken } : undefined)
  const cities = getAllCities(client),

  return {
    props: {
      cities,
      draftMode,
      token: draftMode ? readToken : '',
    },
  }
}

with this working query and type retrieval.

export async function getAllCities(client: SanityClient) {
  const [query, type] = cityBuilder.use()
  return client.fetch<typeof type>(query)
}

Not sure what the best practice is here and I went over the documentation (incl. the cheat sheet) multiple times.
I would appreciate any input! Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants