How to declare custom types in Sanity schema?
No worries, this is a common question when starting with Sanity! Creating custom types is actually straightforward once you understand the pattern.
In Sanity, you define custom types in your schema files using the defineType helper function. For the Personal Website template's "timeline" and "milestone" types, here's how it works:
Basic structure for a custom document type:
import { defineType, defineField } from 'sanity'
export const timeline = defineType({
name: 'timeline',
type: 'document',
title: 'Timeline',
fields: [
defineField({
name: 'title',
type: 'string',
title: 'Title',
}),
// more fields...
],
})For a custom object type (like milestone):
export const milestone = defineType({
name: 'milestone',
type: 'object', // Note: 'object' not 'document'
title: 'Milestone',
fields: [
defineField({
name: 'description',
type: 'string',
title: 'Description',
}),
// more fields...
],
})Key differences:
- Document types (
type: 'document') are top-level content that appear in your Studio and get their own IDs - these are standalone pieces of content - Object types (
type: 'object') are reusable structures that exist within documents - like a milestone inside a timeline
Then register them in your schema:
In your sanity.config.ts (or schema/index.ts):
import { timeline } from './schemas/timeline'
import { milestone } from './schemas/milestone'
export default defineConfig({
// ... other config
schema: {
types: [timeline, milestone],
},
})Common errors to watch for:
- Not importing
defineTypeanddefineFieldfrom 'sanity' - Forgetting to register your types in the schema configuration
- Using
type: 'document'when you needtype: 'object'(or vice versa) - Name conflicts - make sure your
namefield is unique
The defineType function gives you TypeScript autocomplete and helps catch errors early, so always use it even though it's technically optional! If you're still getting errors, double-check that you've registered your types in the schema array and that all your imports are correct.
Show original thread11 replies
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.