Angular7中JointJS自定义形状及链接方法调用报错解决咨询
解决Angular 7中JointJS自定义形状/链接的TypeScript类型错误
你遇到的这些错误都是TypeScript类型系统导致的——JointJS的默认类型定义里没有你自定义的devs.Type、examples.CustomRectangle和devs.Link类型,所以TS会认为这些属性/方法不存在。下面分问题逐个解决:
一、解决devs.Type和examples.CustomRectangle不存在的错误
步骤1:创建自定义类型声明文件
在你的Angular项目的src目录下新建一个类型声明文件,比如jointjs-custom.d.ts,TypeScript会自动识别这个文件并合并类型定义。
步骤2:扩展JointJS的类型接口
在这个文件里添加以下代码,告诉TS你新增了这些自定义形状:
declare namespace joint.shapes { // 扩展devs命名空间,添加Type类型 namespace devs { class Type extends joint.shapes.devs.Model { constructor(attrs?: any); } } // 扩展examples命名空间,添加CustomRectangle类型 namespace examples { class CustomRectangle extends joint.shapes.standard.Rectangle { constructor(attrs?: any); } } }
这样TS就会知道joint.shapes.devs.Type和joint.shapes.examples.CustomRectangle是合法的构造函数了。
二、解决transitionColor不存在于Link类型的错误
你的devs.Link是joint.dia.Link的子类,但graph.getLinks()返回的是joint.dia.Link[]类型,TS无法自动推断这些链接是你自定义的devs.Link实例。可以用两种方法解决:
方法1:类型断言(快速解决)
在调用自定义方法前,把link断言成你的自定义devs.Link类型:
paper.on("link:mouseover", (linkView: any) => { const links = this.graph.getLinks(); links.map(link => { if (link === linkView.model) { return; } // 类型断言为自定义的devs.Link (link as joint.shapes.devs.Link).transitionColor(theme.colors.line.inactive, {duration:500}); link.toBack(); }); });
方法2:完善类型定义(更严谨)
回到之前的jointjs-custom.d.ts,添加devs.Link的类型定义:
declare namespace joint.shapes.devs { class Link extends joint.dia.Link { transitionColor(color: string, options?: { delay?: number, duration?: number }): void; transitionOpacity(opacity: number, options?: { delay?: number, duration?: number }): void; transitionAsync(...args: any[]): Promise<void>; } }
然后在代码里可以先判断链接的类型,再调用方法(更安全,避免类型错误):
paper.on("link:mouseover", (linkView: any) => { const links = this.graph.getLinks(); links.map(link => { if (link === linkView.model) { return; } // 先判断是否为自定义的devs.Link实例 if (link instanceof joint.shapes.devs.Link) { link.transitionColor(theme.colors.line.inactive, {duration:500}); link.toBack(); } }); });
额外注意点
- 确保你的
jointjs-custom.d.ts被包含在tsconfig.app.json的include数组中(默认src/**/*.d.ts会被自动包含,一般不需要额外配置)。 - 如果你使用的是较新的JointJS版本,确保类型定义包
@types/jointjs已经安装(Angular7中应该已经通过npm安装了)。
内容的提问来源于stack exchange,提问作者user824624
相关产品推荐
相关产品推荐

