Angular-4 d3 v4 Issue: Property 'x' does not exist on type 'HierarchyNode'

Viewed 1545

I am trying to create a d3 tree in my angular app, i am trying this example: https://bl.ocks.org/d3noob/08ecb6ea9bb68ba0d9a7e89f344acec8

Problem exists when trying to access the nodes x-y coordinates, i get the error: Property 'x' does not exist on type 'HierarchyNode'

When I log the data, i could see that the x-y coordinates are there. Screenshot showing the logged data

  // declares a tree layout and assigns the size
  var treemap = d3.tree()
    .size([this.height, this.width]);

  //  assigns the data to a hierarchy using parent-child relationships
  var nodes = d3.hierarchy(this.treeData, function(d) {
    return d.children;
    });
  // maps the node data to the tree layout
  nodes = treemap(nodes);
console.log(nodes.descendants());
  // adds each node as a group
  var node = g.selectAll(".node")
    .data(nodes.descendants())
    .enter().append("g")
    .attr("class", function(d) { 
      return "node" + 
        (d.children ? " node--internal" : " node--leaf"); })
    .attr("transform", function(d) { 
      return "translate(" + d.x + "," + d.y + ")"; });

the d.x & d.y produce the error

2 Answers

You can explicitly specify the type to override Contextual Typing

.attr('cx', function (d: HierarchyPointNode<MyDatumInterface>) {
        return d.x // no TS error
    })
Related