I'm struggling to grasp the logic behind a typescript error that keeps popping up - it feels like there's a fundamental concept swiftly flying over my head, making a "whoosh" sound as it goes by.
I stumbled upon this discussion about a similar error, but the scenario described there seems quite different from mine.
Here is the condensed version of the definition I'm referring to.
type ApexAxisChartSeries = {
// ...
data:
| (number | null)[]
| {
x: any;
y: any;
// ...
}[]
| [number, number | null][]
| [number, (number | null)[]][];
}[]
Then there's this problematic function, which expects an array of {x:number, y:number}
.
function composeSeries(input: { x: number; y: number }[]) {
const series: ApexAxisChartSeries = [
{ name: "A", data: [] },
{ name: "B", data: [] },
];
input.forEach((datum) => {
series[0].data.push(datum); // <-- This line right here gives the error.
});
return series;
}
The part that's puzzling me is that according to the type definition, a {x:number, y:number}
object should fit perfectly into the data
array. However, Typescript is raising an issue with the following message:
Argument of type
'{ x: number; y: number; }'
is not assignable to parameter of type.number & { x: any; y: any; fillColor?: string | undefined; strokeColor?: string | undefined; meta?: any; goals?: any; } & [number, number | null] & [number, (number | null)[]]'
Type
'{ x: number; y: number; }'
is not assignable to type'number'
.
And I'm left wondering, where are those intersections in the error message coming from, when the type definition uses unions?
Some additional context:
- It's not just the object causing an error. Even when using
[x,y]
pairs or a simple array of numbers, the compiler still raises red flags - I'm working with TS 4.5.4
- I am confident that the issue lies within this code snippet as the TS playground produces the same error
For your reference, here is the complete type definition:
type ApexAxisChartSeries = {
name?: string
type?: string
color?: string
data:
| (number | null)[]
| {
x: any;
y: any;
fillColor?: string;
strokeColor?: string;
meta?: any;
goals?: any;
}[]
| [number, number | null][]
| [number, (number | null)[]][];
}[]
Any insights or clarity on this matter would be greatly appreciated!
Edit: an example of the error can be found on the TS playground here, courtesy of @jcalz