Vishnu Nair
Vishnu Nair

Reputation: 265

Cannot find name 'line' - d3 line chart

While trying to integrate d3 line chart, the following error is shown. I'm using https://medium.freecodecamp.org/learn-to-create-a-line-chart-using-d3-js-4f43f1ee716b for creating the line chart.

g.append("path")
.datum(data)
.attr("fill", "none")
.attr("stroke", "steelblue")
.attr("stroke-linejoin", "round")
.attr("stroke-linecap", "round")
.attr("stroke-width", 1.5)
.attr("d", line);

This gave the error:

error TS2304: Cannot find name 'line'.

Then I added:

var line = d3.line()
   .x(function(d) { return x(d.date)})
   .y(function(d) { return y(d.value)})
   x.domain(d3.extent(data, function(d) { return d.date }));
   y.domain(d3.extent(data, function(d) { return d.value }));

to my typescript, which resulted in the error:

error TS2339: Property 'date' does not exist on type '[number, number]'

Code for line:

var line = d3.line()
   .x(function(d) { return x(d.date)})
   .y(function(d) { return y(d.value)})
   x.domain(d3.extent(data, function(d) { return d.date }));
   y.domain(d3.extent(data, function(d) { return d.value }));

Any experts in d3.js..? thanks in advance.

Upvotes: 1

Views: 450

Answers (1)

Mark
Mark

Reputation: 108512

Since you are using typescript, you have to tell d3 the type you are passing to the line generator:

var line = d3.line<MyDataType>()
  .x(function(d) {return x(d.date);})
  .y(function(d) {return y(d.value);});

Where MyDataType is the definition of one of your datum, something like:

interface MyDataType{
    date: Date,
    value: number
}

Upvotes: 2

Related Questions