Last time, we manually created the types used in TypeScript in order to complete the sample code. This time, we will generate the types for the defined fields.
This document is a translated version of the official steps explained in Japanese. If you would like to check the English version, we recommend referring to the official page.
Using Sanity TypeGen
Using the Sanity CLI tools, you can generate type definition files for use in TypeScript using the schema definitions defined in Studio.
This procedure is performed entirely in the apps/studio directory.
First, generate a JSON file that will serve as the schema settings.
When complete, a JSON file will be created.

We will create a file that defines type using this file, but since Next.js will be referencing the file this time, we will add the following file to change the output destination.
If the above file exists, the types.ts file will be output to Next.js.
Now that you are ready, execute the following command.
Executing the above command will create a file named apps/web/src/sanity/types.ts.
As a result, the Event interface created in the previous apps/web/src/app/page.tsx file is no longer necessary because sanityFetch returns the shape. Adding the schema causes the following error to appear.

After deleting the definition of the relevant Event, etc., and checking the event again in Visual Studio Code, the definition is referenced correctly as follows.

Automatically update Type
We will proceed with the following edits so that the above tasks are performed automatically when the schema is changed.
This will update the type when you run the following command directly under apps/studio.
When you update the schema, you can easily update the definitions using this procedure.
Summary
This time, we used Sanity's functionality to create TypeScript definitions for use in Next.js from the schema definitions used in Studio. We also added a command to update the schema when changes are made by adding steps to package.json.
The samples shown so far can be found in the following repository/branch.