CoursesTyped content with Sanity TypeGenExtracting your schema
Typed content with Sanity TypeGen

Extracting your schema

Learn how to extract your Sanity Studio schema into a JSON file. This is a crucial step before generating TypeScript types. This file, a static representation of your data's shape, will be used for type generation.
Log in to mark your progress for each Lesson and Task

Before generating TypeScript types for the frontend, you need to extract the Sanity Studio schema written in JavaScript into a static representation, a JSON file describing the shape of the data your Sanity Studio produces.

  • Run the following Sanity CLI command in your studio project folder:
npx sanity schema extract

If your command ran successfully, you should see a new file called schema.json in your Studio project folder. In this course, you will only use this file for the type generation; you don't need to do anything else with it.

While the manual command above is useful for understanding the extraction process, TypeGen can also extract your schema automatically for Studio projects. When you enable automatic extraction through configuration, the schema.json file updates automatically whenever you run sanity dev or sanity build.

Manual extraction remains useful for understanding what's happening under the hood and is especially important for monorepo setups where your Studio and frontend application are in separate packages. In those cases, the schema.json file serves as the bridge between your Studio schema and your frontend types.

We'll cover how to configure automatic schema extraction in a later lesson. For now, the manual command gives you a clear view of the extraction process.

If you explore its content, you will find your Studio schema described in a JSON format. For example, the document type for venue will look something like this:

{
"name": "venue",
"type": "document",
"attributes": {
"_id": {
"type": "objectAttribute",
"value": {
"type": "string"
}
},
"_type": {
"type": "objectAttribute",
"value": {
"type": "string",
"value": "venue"
}
},
"_createdAt": {
"type": "objectAttribute",
"value": {
"type": "string"
}
},
"_updatedAt": {
"type": "objectAttribute",
"value": {
"type": "string"
}
},
"_rev": {
"type": "objectAttribute",
"value": {
"type": "string"
}
},
"name": {
"type": "objectAttribute",
"value": {
"type": "string"
},
"optional": true
},
"city": {
"type": "objectAttribute",
"value": {
"type": "string"
},
"optional": true
},
"country": {
"type": "objectAttribute",
"value": {
"type": "string"
},
"optional": true
}
}
}

This file can be used to develop tooling that needs to know about a Sanity Studio schema. But in this course, you will use it to generate TypeScript types.

Mark lesson as complete
You have 1 uncompleted task in this lesson
0 of 1