GoJS RealtimeDragSelectingTool在TS项目中的导入类型兼容问题
GoJS从JS迁移TS时的RealtimeDragSelectingTool类型冲突问题
我最近把一个项目从JavaScript迁移到TypeScript,之前JS里直接导入gojs/extensions/RealtimeDragSelectingTool,把它赋值给schema.toolManager.dragSelectingTool就能正常用。
转到TS开发后,发现有extensionsTS和extensionsJSM两种导入方式:
- 一开始用
extensionsTS导入,碰到了类型错误,找了相关问题也没明确解答 - 换成
extensionsJSM导入后功能能跑,但IDE里一直报类型不兼容的错误,具体错误信息如下:
Type 'RealtimeDragSelectingTool' is not assignable to type 'DragSelectingTool'. Types of property 'box' are incompatible. Type 'import("c:/Dev/gojs-project/node_modules/gojs/release/go-module").Part | null' is not assignable to type 'go.Part | null'. Type 'import("c:/Dev/gojs-project/node_modules/gojs/release/go-module").Part' is not assignable to type 'go.Part'. The types returned by 'adornments.first()' are incompatible between these types. Type 'import("c:/Dev/gojs-project/node_modules/gojs/release/go-module").Adornment | null' is not assignable to type 'go.Adornment | null'. Type 'import("c:/Dev/gojs-project/node_modules/gojs/release/go-module").Adornment' is not assignable to type 'go.Adornment'. Types of property 'placeholder' are incompatible. Type 'import("c:/Dev/gojs-project/node_modules/gojs/release/go-module").Placeholder | null' is not assignable to type 'go.Placeholder | null'. Type 'import("c:/Dev/gojs-project/node_modules/gojs/release/go-module").Placeholder' is not assignable to type 'go.Placeholder'. Property 'computeBorder' is protected but type 'Placeholder' is not a class derived from 'Placeholder'.ts(2322)
解决办法
统一GoJS相关包版本
这种类型冲突大概率是因为gojs、extensionsTS、extensionsJSM版本不一致导致的,先把三个包的版本统一:npm install gojs@latest gojs/extensionsTS@latest gojs/extensionsJSM@latest配置TS路径别名避免重复导入
在tsconfig.json里加路径别名,让所有GoJS相关导入都指向同一个类型定义文件,防止重复解析导致类型不匹配:{ "compilerOptions": { "paths": { "go": ["./node_modules/gojs/release/go-module.d.ts"], "go/*": ["./node_modules/gojs/*"] } } }用类型断言临时绕过(应急用)
如果上面的方法暂时没效果,用类型断言强制让TS通过编译,不过这只是权宜之计:import { RealtimeDragSelectingTool } from 'gojs/extensionsJSM/RealtimeDragSelectingTool'; // 赋值时做类型断言 schema.toolManager.dragSelectingTool = RealtimeDragSelectingTool as unknown as go.DragSelectingTool;正确使用extensionsTS导入
回到extensionsTS的正确用法,按照官方规范注册工具后再使用:import * as go from 'gojs'; import { RealtimeDragSelectingTool } from 'gojs/extensionsTS/RealtimeDragSelectingTool'; // 先注册工具类 go.Diagram.registerTool('RealtimeDragSelectingTool', RealtimeDragSelectingTool); // 初始化时实例化赋值 schema.toolManager.dragSelectingTool = new RealtimeDragSelectingTool();
内容的提问来源于stack exchange,提问作者C0casio45
相关产品推荐
相关产品推荐

