Home > Net >  Type 'undefined' is not assignable to type '(number | null)[]'
Type 'undefined' is not assignable to type '(number | null)[]'

Time:03-26

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?

CodePudding user response:

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 with undefined 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 were undefined, 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].

CodePudding user response:

values?.**** will return undefined if values is values is nullish (undefined or null). This is the reason for you getting undefined as possible value.

But your data is expected to be of type (number | ScatterDataPoint | BubbleDataPoint | null)[]. So you have to return an array:

const data = values?.map((item: PointDTO) => item.y) ?? []

  • Related