使用Lexical Editor调用registerRichText时出现TypeScript错误:Excessive stack depth comparing types 'LexicalEditor' and 'LexicalEditor'
Lexical Editor调用registerRichText时出现TypeScript错误:Excessive stack depth comparing types 'LexicalEditor' and 'LexicalEditor'
我之前也碰到过这个看起来有点诡异的TypeScript错误——明明都是LexicalEditor类型却报栈深度不匹配,其实大多是依赖版本不一致或者类型导入不规范导致的,下面给你几个可行的解决思路:
1. 确保Lexical相关包版本完全一致
Lexical的各个子包(比如@lexical/core、@lexical/rich-text)版本必须严格对齐,哪怕微小的版本差异都可能导致类型定义冲突。
- 打开你的
package.json,检查@lexical/core和@lexical/rich-text的版本号是否完全相同 - 如果不一致,运行命令统一升级到最新稳定版:
npm install @lexical/core@latest @lexical/rich-text@latest # 或者用yarn yarn add @lexical/core@latest @lexical/rich-text@latest
2. 显式导入正确的LexicalEditor类型
你的代码里可能没有从正确路径导入LexicalEditor类型,导致TypeScript推断的类型和registerRichText期望的类型不兼容。修改导入语句:
// 从@lexical/core显式导入LexicalEditor import { createEditor, LexicalEditor } from '@lexical/core'; import { registerRichText } from '@lexical/rich-text';
这样就能确保你声明的editor变量类型和registerRichText要求的参数类型完全匹配。
3. 清理TypeScript缓存
有时候TypeScript的缓存会残留旧的类型定义,导致奇怪的错误。可以尝试:
- 删除项目根目录下的
node_modules/.cache文件夹(如果用Vite、Webpack等构建工具) - 运行命令清理TS自身的缓存:
npx tsc --clearCache
之后重新编译项目,看看错误是否消失。
4. 临时跳过库类型检查(不推荐长期使用)
如果以上方法都暂时无法解决,可以在tsconfig.json里开启skipLibCheck来跳过第三方库的类型检查,先让项目跑起来:
{ "compilerOptions": { // ...其他配置 "skipLibCheck": true } }
不过这只是临时方案,还是建议优先解决版本或导入的根本问题。
修改后的完整代码示例:
import { createEditor, LexicalEditor } from '@lexical/core'; import { registerRichText } from '@lexical/rich-text'; export class CustomLexicalEditor { private config = { namespace: 'MyEditor', theme: { text: { bold: 'text-bold', italic: 'text-italic', underline: 'text-underline', }, }, onError: console.error, }; initialize( editorContainer: HTMLElement, toolbarContainer: HTMLElement, placeholder?: string, ): void { const editorPlaceholder = placeholder || 'Start typing...'; const editor: LexicalEditor = createEditor(this.config); editor.setRootElement(editorContainer); registerRichText(editor); } }
备注:内容来源于stack exchange,提问作者Cristian David Rodríguez
相关产品推荐
相关产品推荐

