Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Argument of type '[string, string] error? (in Angular and d3)

I am using d3 (version 4) with Angular 5 and am running into some errors that I can't find much information on. In my name.component.ts I have my d3 code, and am getting errors under certain lines.

var x = d3.scaleTime()
  .rangeRound([0, width])
  .domain(d3.extent(this.data, function (d) { return d.date; }));

var y = d3.scaleLinear()
  .rangeRound([height, 0])
  .domain(d3.extent(this.data, function (d) { return d.ratio; }));

For both of these lines, I get the red line under everything inside the domain (d3.extent(this.data, function (d) { return d.ratio; })).

The error is:

Argument of type '[string, string] | [undefined, undefined]' is not 
assignable to parameter of type '(number | Date | { valueOf(): number;}) []'.
Type '[string, string]' is not assignable to type '(number | Date | 
{valueOf(): number; })[]'.
Types of property 'push' are incompatible.
  Type '(...items: string[]) => number' is not assignable to type 
'(...items: (number | Date | { valueOf(): number; })[]) => number'.
    Types of parameters 'items' and 'items' are incompatible.
      Type 'number | Date | { valueOf(): number; }' is not assignable 
to type 'string'.
        Type 'number' is not assignable to type 'string'.

My guess is that there's a clash in date type, but can't figure it out. Any thoughts?

If this helps, here is my entire .ts file:

import { Component, OnInit, Input } from '@angular/core';
import { DataService } from '../data.service';
import { Http } from '@angular/http';
import * as d3 from 'd3';

@Component({
 selector: 'app-name',
 templateUrl: './name.component.html',
 styleUrls: ['./name.component.css']
})
export class Name implements OnInit {
  @Input() site1;

constructor(private _dataService: DataService, private http: Http) { }

date: Date;
dates: any;
value: Number;
eachobj: any;
data: any;
average: any;
values: any;
name: any;
ngOnInit() {

this.data = this.site1
this.dates = Object.keys(this.data.historical_data)
this.values = Object.values(this.data.historical_data)
this.values.forEach((obj, i) => obj.date = this.dates[i]);
this.data = this.values        


var svg = d3.selectAll("#watertemp_graph"),
  margin = { top: 20, right: 20, bottom: 30, left: 0 },
  width = +svg.attr("width") - margin.left - margin.right,
  height = +svg.attr("height") - margin.top - margin.bottom
var parse = d3.timeParse("%Y-%m-%d")
var first = this.data[0].date
var last = this.data[(this.data.length) - 1].date

var g = svg.append("g")
  .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var baseValue = +this.data[0].avg_water_temp;
this.data.forEach(function (d) {
  d.date = parse(d.date);
  d.ratio = +(d.avg_water_temp / baseValue);
});

var x = d3.scaleTime()
  .rangeRound([0, width])
  .domain(d3.extent(this.data, function (d) { return d.date; }));
//ERROR

var y = d3.scaleLinear()
  .rangeRound([height, 0])
  .domain(d3.extent(this.data, function (d) { return d.ratio; }));
//ERROR

var line = d3.line()
  .x(function (d) { return x(d['date']); })
  .y(function (d) { return y(d['ratio']); });


// plot first and last dates on x axis
svg.append('g')
  .attr("class", "axis--x")
  .append("text")
  .attr("fill", "#000")
  .attr("x", (width / 2) - 80)
  .attr("y", height + 40)
  .text(first)
  .style("font-size", "09")
  .style("font-family", "Roboto")
  .style('fill', '#5a5a5a');
svg.append('g')
  .attr("class", "axis--x")
  .append("text")
  .attr("fill", "#000")
  .attr("x", (width / 2) + 45)
  .attr("y", height + 40)
  .text(last)
  .style("font-size", "09")
  .style("font-family", "Roboto")
  .style('fill', '#5a5a5a');


g.append("g")
  .call(d3.axisLeft(y))
  .remove();

g.append("path")
  .datum(this.data)
  .attr("fill", "none")
  .attr("stroke", "#26aae2")
  .attr("stroke-width", 1.5)
  .attr("d", line);

 }

}
like image 957
LaurenAH Avatar asked Sep 01 '18 03:09

LaurenAH


1 Answers

d3.extent has two overloads that take two parameters:

export function extent<T>(array: ArrayLike<T>,
  accessor: (datum: T, index: number, array: ArrayLike<T>) => string | undefined | null):
  [string, string] | [undefined, undefined];

export function extent<T, U extends Numeric>(array: ArrayLike<T>,
  accessor: (datum: T, index: number, array: ArrayLike<T>) => U | undefined | null):
  [U, U] | [undefined, undefined];

TypeScript always resolves a call to the first matching overload, and since this.data is declared as type any, TypeScript is unable to rule out that the first overload matches. This is where the [string, string] is coming from. If you specify a more precise type for this.data, the first call should resolve to the second overload and the return type should come out as the expected [Date, Date] | [undefined, undefined]. You'll still need a type assertion to assert that the result is [Date, Date] and not [undefined, undefined]; I'm not aware of any reasonable way to do this with narrowing. So your code would look like:

var x = d3.scaleTime()
  .rangeRound([0, width])
  .domain(<[Date, Date]>d3.extent(this.data, function (d) { return d.date; }));

Given that you need the type assertion, you could leave this.data as any, though it would be better practice in general to give it a proper type. Analogous remarks apply to the second call to d3.extent.

like image 118
Matt McCutchen Avatar answered Oct 21 '22 22:10

Matt McCutchen