我在使用 d3.hierarchy
时尝试使用正确的 ts 类型具有树状布局的根,例如:
interface MyCustomGraphType {
id: string;
children?: MyCustomGraphType[]
}
let treeData: MyCustomGraphType = {/*...*/};
let root = d3.hierarchy(treeData);
let layout = d3.tree().size([500,500])(root);
let nodes = layout.descendants();
// BIND DATA (Node)
let node = this.nodesGroup.selectAll('g.node')
.data(nodes, d => d.data.person.email); // <--- compile-time error
// ^^^ Property 'data' does not exist on type '{} | HierarchyNode<MyCustomGraphType>'.
// ... later:
node.enter()
.append('circle')
.attr('transform', d => `translate(${d.x}, ${d.y})`); // <--- compile-time error
// ^^^ Property 'y' does not exist on type '{} | HierarchyNode<MyCustomGraphType>'.
显然第一个错误是因为联合类型 '{} | HierarchyNode<MyCustomGraphType>'
出于某种原因在 key
中推断功能。第二个错误是由于 d3.tree
添加以前未在此处定义的属性。
在保持类型安全的同时解决这个问题的干净方法是什么?
谢谢!
附言我正在使用 d3 版本 4
最佳答案
这里发生了一些事情,应该很容易解决:
(1) 澄清一下,我假设您的实际数据结构更像是这样:
interface MyCustomGraphType {
id: string;
person: {
email: string;
/*Other Properties*/
};
children?: MyCustomGraphType[];
}
这将解释您访问 person.email
selection.data(...)
中节点的属性关键功能。
(2) D3 定义广泛使用泛型类型参数。在某些情况下,类型推断会很容易地为他们服务。在其他情况下,它们不能轻易推断出来。
- 使用
d3.tree<MyCustomGraphType>().size([500,500])(root);
这将返回类型为HierarchyPointNode<MyCustomGraphType>
的树布局根点。 .言外之意nodes
现在将是HierarchyPointNode<MyCustomGraphType>[]
数组。 -
select
,selectAll
,append
和data
来自 d3-selection 模块的 JSDoc 对各种重载签名的泛型有广泛的评论。它们应该在代码编辑器(例如 VS Code)中以鼠标悬停提示或类似方式提供。
(3) data
中key accessor的原因方法调用错误出来,如下: key accessor 用于匹配old 和new 数据条目。旧数据类型基于前面的selectAll(...)
陈述。鉴于所选元素的通用类型及其“旧”数据类型无法从基于字符串的选择器中推断出来,因此必须明确设置它们。否则,“旧”数据类型默认为 {}
.这就是您看到联合数据类型 {} | HierarchyPointNode<MyCustomGraphType>
的原因.必须注意所选元素的“旧”数据类型在实际所选元素和键访问器之间是同步的。如果需要,关键函数应该有办法处理边缘情况。
(4) 至于缺失的属性x
或 y
,我似乎无法复制这个问题。对我来说,它们作为 d
的数据类型存在在
attr('transform', d => `translate(${d.x}, ${d.y})`)
被正确推断为 HierarchyPointNode<MyCustomGraphType>
.
希望这能解释。
关于typescript - d3 (v4) 树布局和 typescript : Property 'x' does not exist on type 'HierarchyNode<IOrgChartNode>' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45356346/