How to use date in x value for Object[] in chartjs dataset, I am getting an error: 'TS2322: Type 'string' is not assignable to type 'number'.'

How to use date in x value for Object[] in chartjs dataset, I am getting an error: 'TS2322: Type 'string' is not assignable to type 'number'.'

我目前正在尝试为 Chartjs 中的数据集实现 Object[] 而不是 Primitive[]。我将 Angular 与 Chart.js 3.6.0 和 ng2-charts 3.0.0-rc.7

结合使用

行-chart.component.ts:

import { ChartConfiguration, ChartType } from 'chart.js';
import { BaseChartDirective } from 'ng2-charts';
import * as moment from "moment";

@Component({
  selector: 'app-line-chart',
  templateUrl: './line-chart.component.html',
  styleUrls: ['./line-chart.component.scss']
})
export class LineChartComponent implements OnInit {
....

public lineChartData: ChartConfiguration['data'] = {
    datasets: [
      {
        data: [
          {x: '2021', y: 12}, > TS2322: Type 'string' is not assignable to type 'number'.
        ],
        label: 'FBSV',
      }
    ],
    // empty for for dynamic structuring.
    labels: []
  };

public lineChartOptions: ChartConfiguration['options'] = {
    plugins: {
      title: {
        display: true,
        text: this.title,
        color: '#25167A',
        font: {
          size: 15,
          weight: 'bold'
        }
      },
    },
    elements: {
      line: {
        tension: 0.25 // creates smoother lines
      }
    },
    scales: {
      x: {
        display: true,
        title: {
          display: true,
          text: 'Year',
          color: '#25167A',
          font: {
            size: 15,
            weight: 'bold'
          }
        },
        type: 'time',
        time: {
          unit: 'year'
        }
      },
      y: {
        display: true,
        title: {
          display: true,
          text: 'Score',
          color: '#25167A',
          font: {
            size: 15,
            weight: 'bold'
          }
        },
        max: 100,
        min: 0,
        beginAtZero: true
      }
    }
  };

  public lineChartType: ChartType = 'line';

  @ViewChild(BaseChartDirective) chart?: BaseChartDirective;

....

问题是在 Chart.js 3.6.0 文档中声明您应该能够使用非原始数据值: https://www.chartjs.org/docs/latest/general/data-structures.html

行-chart.component.html:

<canvas baseChart
              [data]="lineChartData"
              [options]="lineChartOptions"
              [type]="lineChartType">
      </canvas>

如何解决此问题以便能够在 x 值中使用日期?

您可以将自己的类型作为第二个参数传递给 ChartConfiguration 接口,如下所示:

const lineChartData: ChartConfiguration<"line", { x: string, y: number }[]> = {
  type: "line",
  data: {
    labels: [],
    datasets: [
      {
        data: [
          { x: "test", y: 55 },
          { x: "hi", y: 20 },
        ],
      },
    ],
  },
};

Typescript playground link