
Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag storeYou'll want to use Sanity TypeGen to automatically generate TypeScript types for your posts! This is the recommended approach that eliminates manual type definitions.
First, generate types from your schema and queries:
npx sanity typegen generateThis creates a sanity.types.ts file with types for all your schema documents.
Here's how to properly type your component using the generated types:
import { defineQuery } from 'next-sanity'
import type { POST_QUERYResult } from '@/sanity.types' // adjust path as needed
const POST_QUERY = defineQuery(`*[_type == "post"] | order(publishedAt desc)`)
export async function getStaticProps() {
const posts = await sanity.fetch(POST_QUERY);
// posts is now automatically typed!
return {
props: {
posts
}
};
}
interface IndexProps {
posts: POST_QUERYResult
}
export default function Index({ posts }: IndexProps) {
return (
<div>
<h1>Welcome to a blog!</h1>
{posts.map(({ _id, title = '', slug, _updatedAt = '' }) =>
slug && (
<li key={_id}>
<Link href={`/blog/post/${slug.current}`}>
{title}
</Link>{' '}
({new Date(_updatedAt).toDateString()})
</li>
)
)}
</div>
);
}The defineQuery helper does two things:
When you run npx sanity typegen generate, it scans your code for defineQuery calls and creates corresponding TypeScript types named after your variable (e.g., POST_QUERY becomes POST_QUERYResult).
npx sanity typegen generate whenever you change your schema or queriespackage.json: "typegen": "sanity typegen generate"client.fetch(), so TypeScript knows exactly what shape your data isThis approach is much better than manually creating types because your types stay in sync with your actual schema and queries automatically! If you want more control over runtime validation, there's also groqd, but for most cases the built-in TypeGen is the way to go.
Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.
Content operations
Content backend


The only platform powering content operations
By Industry


Tecovas strengthens their customer connections
Build and Share

Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag store