I'm currently utilizing chart.js along with these libraries/versions in my Vite/React TypeScript project:
- chart.js: 4.3.0
- react-chartjs-2: 5.2.0
- chartjs-adapter-date-fns: 3.0.0
- chartjs-plugin-datalabels: 2.2.0
I'm facing a dilemma as I aim to use a Line chart with a "time" type, where the datasets' x
values are strings (formatted dates) and the datasets' y
values are numbers.
I made sure to be clear in how I declared the datasets:
const data: ChartData<"line", StatPointDto[]> = {
datasets: [
{
...
data: props.data.ios,
...
},
{
...
data: props.data.android,
...
},
] as ChartDataset<"line", StatPointDto[]>[],
};
props.data.ios
and props.data.android
are both StatPointDto[]
.
The StatPointDto
class, which I utilize in my project, is structured as follows:
export class StatPointDto {
public x: string;
public y: number;
constructor(x: string, y: number) {
this.x = x;
this.y = y;
}
}
This is how I've defined my chart, straightforwardly:
<Line
data={chartData}
options={chartOptions}
/>
However, with this ChartData arrangement, I encounter a TypeScript type mismatch error:
Types of property 'data' are incompatible.
Type 'StatPointDto[]' is not assignable to type '(number | Point | null)[]'.
Type 'StatPointDto' is not assignable to type 'number | Point | null'.
Type 'StatPointDto' is not assignable to type 'Point'.
Types of property 'x' are incompatible.
Type 'string' is not assignable to type 'number'.
Upon inspection, it appears that Chart.js expects my dataset elements to be either numbers, Points
, or nulls.
The Chart.js Point
definition features x
and y
as numbers, but as this is a time series, my x
values are strings, which leads to the issue.
How can I properly pass my points data with x
values as strings (dates) and y
values as numbers, without running into TypeScript errors?
Note: this should be supported, as per https://www.chartjs.org/docs/latest/general/data-structures.html#typescript
Thank you in advance!