Reputation: 1
I am running into a problem creating a line graph.
First, my return d.x
and return d.y
does not work. I get the error:
Property 'x' does not exist on type '[number, number]' .
Interface code:
export interface TestItem { "x": number, "y": number }
Sample Data:
let lineData = [{
"x": 1,
"y": 5
}, {
"x": 20,
"y": 20
}, {
"x": 40,
"y": 10
}, {
"x": 60,
"y": 40
}, {
"x": 80,
"y": 5
}, {
"x": 100,
"y": 60
}];
Line command:
let svgLine = d3.svg.line().x(function(d) {
return d.x;
})
.y(function(d) {
return d.y;
})
.interpolate("linear");
Second Issue: my append path command also has a problem:
The svgLine(lineData)
as the following error:
Argument of type '{ "x": number; "y": number; }[]' is not assignable to parameter of type '[number, number][]'. Type '{ "x": number; "y": number; }' is not assignable to type '[number, number]'. Property '0' is missing in type '{ "x": number; "y": number; }'.
I have referenced multiple examples and they all have the same code. So I'm not sure what the problem is.
Upvotes: 0
Views: 1107
Reputation: 21578
Looking at the type definitions for D3 v3 one notices that a d3.svg.line()
generator comes in two flavors: (1) either using the default type [number, number]
or (2) by specifying your own type:
namespace svg {
export function line(): Line<[number, number]>; // (1)
export function line<T>(): Line<T>; // (2)
Since you have not provided any type argument when creating the line generator in your statement
let svgLine = d3.svg.line()
the TypeScript compiler will use the above case (1) assuming your data be in a tuple containing two numbers.
This clearly conflicts with your data structure in lineData
which is an array of objects, not an array of well-defined tuples. Hence, the compiler errors you witnessed.
As can be seen from the declarations the workaround for this is simple. You can easily pass in your interface TestItem
to initialize the line generator to the appropriate type:
let svgLine = d3.svg.line()<TestItem>
.x(function(d) { return d.x; })
.y(function(d) { return d.y; })
.interpolate("linear");
Upvotes: 2