Sanity CMS defineType中fields与of的TypeScript类型不匹配错误修复
问题分析
你遇到的image.fields和bio.of类型不匹配错误,是因为Sanity v3的Schema定义需要严格遵循TypeScript类型规范,尤其是字段嵌套和富文本结构的类型声明。结合你使用的版本(sanity 3.44.0、@sanity/types 3.44.0),以下是针对性的修正方案。
修正后的author.ts Schema代码
import {defineType, defineField} from 'sanity' import {UserIcon} from '@sanity/icons' export default defineType({ name: 'author', title: 'Author', type: 'document', icon: UserIcon, fields: [ defineField({ name: 'name', title: 'Name', type: 'string', validation: Rule => Rule.required(), }), defineField({ name: 'slug', title: 'Slug', type: 'slug', options: { source: 'name', maxLength: 96, }, validation: Rule => Rule.required(), }), // 修正后的image字段:确保fields使用defineField包裹,类型匹配 defineField({ name: 'image', title: 'Image', type: 'image', options: { hotspot: true, }, fields: [ defineField({ name: 'alt', title: 'Alt Text', type: 'string', validation: Rule => Rule.required(), }), ], }), // 修正后的bio字段:正确声明富文本的block类型 defineField({ name: 'bio', title: 'Bio', type: 'array', of: [ defineField({ type: 'block', styles: [{title: 'Normal', value: 'normal'}], lists: [], }), ], validation: Rule => Rule.max(300), }), ], preview: { select: { title: 'name', media: 'image', }, }, })
关键修正点
- image字段的fields:必须用
defineField包裹每个子字段,确保类型符合ImageFieldDefinition的要求。之前的错误大概率是直接使用普通对象而非defineField生成的字段定义。 - bio字段的of:富文本数组的每个元素必须是
defineField声明的block类型,明确指定styles和lists(不需要列表可设为空数组),避免TypeScript推断出不兼容类型。 - 类型导入规范:始终从
sanity导入defineType和defineField,这两个方法会自动处理类型推导,避免手动声明类型时的错误。
额外验证步骤
- 确认所有Schema文件都用
defineType包裹顶层文档类型,defineField包裹每个字段。 - 若自定义了富文本block类型,需确保其符合
BlockDefinition规范,比如正确设置type: 'block'。 - 运行
npm run type-check(或yarn type-check)验证修正后的类型匹配情况,确认无残留警告。
内容的提问来源于stack exchange,提问作者Avtar
相关产品推荐
相关产品推荐

