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

将myDecorator作为decorate传入React Slate时出现TS错误

TypeScript类型错误修复方案(针对Editable组件decorate属性)

错误信息

(property) decorate?: ((entry: NodeEntry<Node>) => BaseRange[]) | undefined
类型 '([node, path]: [node: any, path: any]) => { anchor: { path: any; offset: string | number; }; focus: { path: any; offset: string; }; decoration: string; }[]' 不能赋值给类型 '(entry: NodeEntry<Node>) => BaseRange[]'。
  类型 '{ anchor: { path: any; offset: string | number; }; focus: { path: any; offset: string; }; decoration: string; }[]' 不能赋值给类型 'BaseRange[]'。
    类型 '{ anchor: { path: any; offset: string | number; }; focus: { path: any; offset: string; }; decoration: string; }' 不能赋值给类型 'BaseRange'。
      'anchor.offset' 的类型不兼容。
        类型 'string | number' 不能赋值给类型 'number'。
          类型 'string' 不能赋值给类型 'number'。ts(2322)
editable.d.ts(34, 5): 预期类型来自属性 'decorate',该属性在类型 'IntrinsicAttributes & { decorate?: ((entry: NodeEntry<Node>) => BaseRange[]) | undefined; onDOMBeforeInput?: ((event: InputEvent) => void) | undefined; ... 8 more ...; as?: ElementType<...> | undefined; } & TextareaHTMLAttributes<...> & MUIStyledCommonProps<...> & { ...; }' 上声明。

错误场景

错误出现在Editable组件的decorate属性绑定处:

<Editable
  decorate={myDecorator}

错误原因

  1. BaseRange类型强制要求anchor.offset和focus.offset为数字类型,但myDecorator返回的对象中,这两个参数是string | number或纯string类型,类型不匹配。
  2. decorate回调的参数未指定正确类型,用any替代了NodeEntry<Node>,导致后续类型推断失效。

修复步骤

  1. 修正offset类型:确保anchor.offset和focus.offset始终为数字。如果是字符串来源,用parseInt()或Number()做类型转换:
// 错误写法
offset: someStringValue
// 修复后
offset: parseInt(someStringValue, 10) // 或 Number(someStringValue)
  1. 指定回调参数类型:给myDecorator的参数加上NodeEntry<Node>类型约束,替换any:
import { NodeEntry, BaseRange } from 'slate'

const myDecorator = ([node, path]: NodeEntry<Node>): BaseRange[] => {
  // 装饰逻辑,确保返回的每个range的offset都是数字
  return [
    {
      anchor: { path, offset: 0 },
      focus: { path, offset: node.text.length },
      decoration: 'highlight'
    }
  ]
}
  1. 校验返回值结构:确认返回的每个对象严格匹配BaseRange类型,移除多余属性(若存在)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 18:35:50