“Property does not exist on type {}” error when us

2019-07-31 06:53发布

问题:

I'm trying to create D3 SVG Symbols, with the symbol shape set dynamically based on a category property in the data. This will be part of a custom visual in PowerBI, so I'm using Typings library.

From the examples I've seen online, the below code should work.

var milestoneSymbols = this.milestoneContainer.selectAll('.path').data(viewModel.milestones);
milestoneSymbols.enter().append('path');
milestoneSymbols.attr('d', d3.svg.symbol() 
                            .size(25) 
                            .type( function(d){ return d.typeSymbol})
    );
milestoneSymbols.attr("transform", function(d,i) {
        return "translate("+ xScale(d.date) + "," 
            + ((i % heightGroups) * (milestoneContainerHeight/heightGroups) + margins.top )
            + ")";
        });
milestoneSymbols.style("stroke", "function(d) {  return findTaskTypeShape(d.label).color; }
                .style("stroke-width", 1)
                .style("fill", function(d) {  return findTaskTypeShape(d.label).color; });

But I get the error Property 'typeSymbol' does not exist on type '{}' for the code .type( function(d){ return d.typeSymbol}). It appears that d is not available inside type() because it's being used in the d3.svg.symbol() code. If I replace the anonymous function with a string literal like "square", it works.

How can this be fixed?

回答1:

Typescript does not know anything about your data object type. You can define the data object type or you could try to use the type any:

milestoneSymbols.attr('d', d3.svg.symbol() 
                            .size(25) 
                            .type( function(d: any){ return d.typeSymbol;})