Angular 2 typescript d3 type issue: Property 'x' does not exist on type '[number, number]'

前端 未结 6 1162
小鲜肉
小鲜肉 2021-01-11 15:15

I am generating a line chart with d3. It works, but typescript code complain about a property not exists in vs.

Property \'x\' does not exist on type

相关标签:
6条回答
  • 2021-01-11 15:46

    .x((d:any) => this.xScale(d.x)) .y((d:any) => this.yScale(d.y))

    0 讨论(0)
  • 2021-01-11 15:49

    its a typescript error.

    i think there is no x property right now in your d. can you try this

     return this.xScale(d?.x);
     return this.xScale(d?.y);
    

    or may be your d have data like this ["x_value","y_value"] in number format.

    in this case you should try

    return this.xScale(d[0]);
    return this.yScale(d[1]);
    

    i hope this will help

    0 讨论(0)
  • 2021-01-11 15:52

    As said, it's a TypeScript interpretation issue. I simply fixed it using brackets notation to access the property. Just like this:

    let line = d3.line()
      .x(function (d) {
        return x(d['date']);
      })
      .y(function (d) {
        return y(d['temp']);
      });
    
    0 讨论(0)
  • 2021-01-11 15:52

    The best way is use Typescript Optional operator ( ? ).

    function buildName(firstName: string, lastName?: string) {
        if (lastName)
            return firenter code herestName + " " + lastName;
        else
            return firstName;
    }
    
    let result1 = buildName("Bob");                  // works correctly now
    let result2 = buildName("Bob", "Adams", "Sr."); // error, too many parameters
    let result3 = buildName("Bob", "Adams");    // ah, just right
    

    For more details https://www.typescriptlang.org/docs/handbook/functions.html

    0 讨论(0)
  • 2021-01-11 16:03

    When data is passed as a variable, defining that data as type any should appease TypeScript, e.g.:

    // Append a 'text' SVGElement with data-driven text() to each 'g' SVGElement 
    d3.selectAll('g')
      .each(function(d: any) {
        d3.select(this)
          .append('text')
          .text(d.mytext);
      });
    
    
    0 讨论(0)
  • 2021-01-11 16:09

    Here is the solution. I need to use generics:

    0 讨论(0)
提交回复
热议问题