Renaud is Not Bill Gates
Renaud is Not Bill Gates

Reputation: 2084

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

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?

Upvotes: 2

Views: 12052

Answers (3)

Ovidijus Parsiunas
Ovidijus Parsiunas

Reputation: 2742

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].

Upvotes: 2

Tushar Shahi
Tushar Shahi

Reputation: 20701

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) ?? []

Upvotes: 0

shieldgenerator7
shieldgenerator7

Reputation: 1756

You might have to specify that the variable is undefinable:

    let dataPoint: DataPoint | undefined;

Upvotes: 0

Related Questions