Issue
I have TS complaining about this code:
const data = values?.map((item: PointDTO) => item.y);
const chartData: ChartData = {
labels,
datasets: [{ data }],
};
The error message is :
Type '(number | undefined)[] | undefined' is not assignable to type '(number | ScatterDataPoint | BubbleDataPoint | null)[]'.
Type 'undefined' is not assignable to type '(number | null)[]'
So I changed my code to:
const data = values?.map((item: PointDTO) => item.y) ?? null;
But this didn’t solve my issue.
How can I solve this please?
Solution
Assuming that the following line is the one that is displaying the error:
datasets: [{ data }],
you will need to change the first line of your example to the following:
const data = values?.map((item: PointDTO) => item.y).filter((y) => y !== undefined) ?? [];
Explanation to changes:
- If the
values
variable was set to null –data
would have originally been assigned withundefined
by the optional operator. This is fixed by adding?? []
at the end which will default the result to an empty array instead. - If any of the
item.y
properties wereundefined
,data
would have originally been assigned with an array that contains undefined values as follows[undefined, undefined, 1234, undefined]
. This is fixed by.filter((y) => y !== undefined)
which removes any of the undefined entries from the array and would change the previous result to this[1234]
.
Answered By – Ovidijus Parsiunas
Answer Checked By – Gilberto Lyons (BugsFixing Admin)