cod*_*pic 0 javascript d3.js angularjs typescript
我正在尝试显示一个饼图并且它实际上正在工作,即使我收到 TypeScript 编译错误: Argument of type '(d: any) => {}' is not assignable to parameter of type 'datum: Arc<number>, index: number, outerIndex: number) => number | string | boolean'. Type '{}' is not assignable to type 'number | string | boolean'. Type '{}' is not assignable to type 'boolean'.
过去 2 年我一直在使用 TypeScript,但上面的行让我头晕目眩。我不知道发生了什么,我尝试了几件事,但到目前为止没有任何效果。
这是实际绘制饼图的代码:
function drawChart(){
var width = 960,
height = 500,
radius = Math.min(width, height) / 2;
var colourValues = d3.scale.ordinal().range(d3.values(that.ColoursService.colours));
var arc = d3.svg.arc()
.outerRadius(radius - 10)
.innerRadius(radius - 70);
var pie = d3.layout.pie()
.sort(null)
.value(function(d: any) {return d.quantity});
var svg = d3.select('.pie-chart').append('svg')
.attr('width', width)
.attr('height', height)
.append('g')
.attr('transform', 'translate(' + width / 2 + ',' + height/2 + ')');
var g = svg.selectAll('.arc')
.data(pie(data))
.enter().append('g')
.attr('class', 'arc');
g.append('path')
.attr('d', <any>arc)
.attr('fill', function(d: any) {
return colourValues(d.data.category);
});
}
Run Code Online (Sandbox Code Playgroud)
这是打字稿突出显示错误的地方,波浪线出现在“功能”词下方。我需要让 TypeScript 编译器通过,但我不知道如何通过。
尽管使用<any>会消除编译器的抱怨,但您基本上是在回避强类型检查,这可以说是首先使用 Typescript 的要点之一。我这个问题挣扎了很久,最后,经过反复试验和大量的质量与时间的d3.d.ts定义d3.svg.arc,能想出一种方法,使所有类型的排队。这是一个演示如何在不使用<any>. 关键是您需要指定一个interface描述输入形状的,即您的数据:
interface Datum {
category: string;
quantity: number;
}
function drawChart(data: Array<Datum>) {
let width = 960,
height = 500,
radius = Math.min(width, height) / 2,
colourValues = d3.scale.category10();
// specify Datum as shape of data
let arc = d3.svg.arc<d3.layout.pie.Arc<Datum>>()
.innerRadius(radius - 70)
.outerRadius(radius - 10);
// notice accessor receives d of type Datum
let pie = d3.layout.pie<Datum>().sort(null).value((d: Datum):number => d.quantity);
// note input to all .attr() and .text() functions
// will be of type d3.layout.pie.Arc<Datum>
let fill = (d: d3.layout.pie.Arc<Datum>): string => colourValues(d.data.category);
let tfx = (d: d3.layout.pie.Arc<Datum>): string => `translate(${arc.centroid(d)})`;
let text = (d: d3.layout.pie.Arc<Datum>): string => d.data.category;
let svg = d3.select('.pie-chart').append('svg')
.attr('width', width)
.attr('height', height)
.append('g')
.attr('transform', 'translate(' + width / 2 + ',' + height / 2 + ')');
// create a group for the pie chart
let g = svg.selectAll('.arc')
.data(pie(data))
.enter().append('g').attr('class', 'arc');
// add pie sections
g.append('path').attr('d', arc).attr('fill', fill);
// add labels
g.append('text').attr('transform', tfx).text(text);
}
Run Code Online (Sandbox Code Playgroud)
请注意,我将您的替换ColourService为标准d3颜色类别函数之一,但只要colourValues()返回指定填充颜色的字符串,它仍然可以工作。
希望这个例子展示了如何让你的自定义数据类型d3和 Typescript一起工作。
| 归档时间: |
|
| 查看次数: |
2135 次 |
| 最近记录: |