How to get schema types into a TypeScript project with a React.js app and Sanity.io
Totally feel your pain! The good news is that Sanity has an official built-in solution called TypeGen that should solve this for you. The sanity-codegen package you tried is an older third-party tool that's not maintained for Sanity v3, which explains the errors.
Here's the modern approach using Sanity's official TypeGen:
Quick Setup (2 steps)
1. Extract your schema (run this in your Sanity project folder):
npx sanity@latest schema extractThis creates a schema.json file with your schema structure.
2. Generate TypeScript types:
npx sanity@latest typegen generateThis creates a sanity.types.ts file with all your schema types! 🎉
Using the Types in Your React App
After generation, you can import and use the types:
import type { Post, Author } from './sanity.types'
// Type-safe document creation
await client.create<Post>({
_type: "post",
title: "My Post",
// TypeScript will autocomplete and validate fields!
})Multi-Folder Setup (Sanity + React in separate folders)
If your Sanity studio and React app are in different folders, create a sanity-typegen.json in your Sanity project:
{
"path": "../my-react-app/src/**/*.{ts,tsx}",
"schema": "./schema.json",
"generates": "../my-react-app/src/sanity/sanity.types.ts"
}This tells TypeGen where to find your React files and where to output the types.
Bonus: Type-Safe GROQ Queries
For even better DX, wrap your GROQ queries with defineQuery to get typed query results:
import { defineQuery } from 'groq'
const postsQuery = defineQuery(`*[_type == "post"]{ title, author-> }`)
// TypeGen will generate types for this query result!
const posts = await client.fetch(postsQuery)Requirements
You'll need Sanity CLI version 3.35.0 or later. Update if needed:
npm install -g sanity@latestPro tip: Run sanity typegen generate whenever you change your schema to keep types in sync. You can also use sanity typegen generate --watch during development to automatically regenerate types when your schema changes!
Sanity – Build the way you think, not the way your CMS thinks
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.