Reputation: 1774
I'm using chart.js with the following libraries/versions in my Vite/React project in TypeScript:
I'm in a pickle right now because I want to use a Line chart with "time" type, so my datasets' x
are strings (formatted dates) and my datasets' y
are numbers.
I tried to be as explicit as I could when declaring 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[]
.
StatPointDto
is a simple wrapper class that I use in my project, defined as follows:
export class StatPointDto {
public x: string;
public y: number;
constructor(x: string, y: number) {
this.x = x;
this.y = y;
}
}
My chart is declared as follows, nothing fancy:
<Line
data={chartData}
options={chartOptions}
/>
With this ChartData setup, I get 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'.
By reading, I see that Chart.js wants my dataset elements to be either numbers, Points
, or nulls.
The Point
definition of Chart.js has x
and y
as numbers but since this is a time series, I have x
strings, which just does not work.
What can I do to pass my points data properly, considering x
values are strings (dates) and y
values are numbers, without being yelled at by TypeScript?
Note: this is supposed to be allowed, according to https://www.chartjs.org/docs/latest/general/data-structures.html#typescript
Thanks in advance!
Upvotes: 0
Views: 619
Reputation: 1774
My bad, the error was coming from something else, in my case
it was coming from this declaration using the React useState
hook:
const [chartData, setChartData] = useState<ChartData<"line">>({
datasets: [],
});
Which was incomplete, causing a type inconsistency in my code. I fixed it by writing:
const [chartData, setChartData] = useState<ChartData<"line", StatPointDto[]>>({
datasets: [],
});
Upvotes: 3