javascript – 使用d3.js和TypeScript绘制饼图时的编译错误

前端之家收集整理的这篇文章主要介绍了javascript – 使用d3.js和TypeScript绘制饼图时的编译错误前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图使用d3.js库和TypeScript绘制饼图.我有以下代码: @H_404_2@"use strict"; module Chart { export class chart { private chart: d3.Selection<string>; private width: number; private height: number; private radius: number; private donutWidth: number; private dataset: { label: string,count: number }[]; private color: d3.scale.Ordinal<string,string>; constructor(container: any) { this.width = 360; this.height = 360; this.radius = Math.min(this.width,this.height) / 2; this.donutWidth = 75; this.dataset = [ { label: 'Road',count: 5500 },{ label: 'Bridge',count: 8800 },{ label: 'Tunnel',count: 225 },]; this.color = d3.scale.category10(); this.init(container); } private init(container) { this.chart = d3.select(container).append('svg') .attr('width',this.width) .attr('height',this.height) .append('g') .attr('transform','translate(' + (this.width / 2) + ',' + (this.height / 2) + ')'); } draw() { var arc = d3.svg.arc() .innerRadius(this.radius - this.donutWidth) // NEW .outerRadius(this.radius); var pie = d3.layout.pie() .sort(null); var path = this.chart.selectAll('path') .data(pie(this.dataset.map(function(n) { return n.count; }))) .enter() .append('path') .attr('d',arc) .attr('fill',function(d,i) { return Math.random(); }); } } }

代码不会与错误一起编译:

@H_404_2@Argument of type 'Arc<Arc>' is not assignable to parameter of type '(datum: Arc<number>,index: number,outerIndex: number) => string | number | boolean'. >> Types of parameters 'd' and 'datum' are incompatible. >> Type 'Arc' is not assignable to type 'Arc<number>'. >> Property 'value' is missing in type 'Arc'.

当我尝试将d属性添加到我的svg上的每个路径元素时,出现编译错误

@H_404_2@var path = this.chart.selectAll('path') .data(pie(this.dataset.map(function(n) { return n.count; }))) .enter() .append('path') .attr('d',i) { return Math.random(); });

根据文档,弧是“既是对象又是函数”.我看到我可以通过调用arc(datum [,index])来访问它,例如只需要对arc [0]进行硬编码.当我这样做时,我的编译错误消失但是svg中每个路径元素的d属性都丢失了,我最终得到了一个像svg:

@H_404_2@<svg height="360" width="360"> <g transform="translate(180,180)"> <path fill="0.35327279710072423"></path> <path fill="0.6333000506884181"></path> <path fill="0.9358429045830001"></path> </g> </svg>

我已经将代码作为纯JavaScript运行而没有任何问题.

解决方法

尝试更换 @H_404_2@.attr('d',arc)

@H_404_2@.attr('d',<any>arc)

这隐藏了我的计算机上的编译器错误,但如果这实际上工作……好吧,我不知道.

我对这个问题的理解是你提供了带有数字值的.data函数,TypeScript编译器希望.attr也包含一个数字,但是你提供了一个弧.

猜你在找的JavaScript相关文章