You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Sanity CMS defineType中fields与of的TypeScript类型不匹配错误修复

解决Sanity CMS Author Schema的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,这两个方法会自动处理类型推导,避免手动声明类型时的错误。

额外验证步骤

  1. 确认所有Schema文件都用defineType包裹顶层文档类型,defineField包裹每个字段。
  2. 若自定义了富文本block类型,需确保其符合BlockDefinition规范,比如正确设置type: 'block'。
  3. 运行npm run type-check(或yarn type-check)验证修正后的类型匹配情况,确认无残留警告。

内容的提问来源于stack exchange,提问作者Avtar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 11:49:57