Search code examples
typescriptng-apexcharts

How can I access the property `data` in this type?


I have this type which comes from a lib:

export interface AllChartOptions {
  series: ApexAxisChartSeries | ApexNonAxisChartSeries;
  ...
}

And here is the type of series

export declare type ApexAxisChartSeries = {
    name?: string;
    type?: string;
    color?: string;
    group?: string;
    data: (number | null)[] | {
        x: any;
        y: any;
        ...
    }[] | [number, number | null][] | [number, (number | null)[]][] | number[][];
}[];
export declare type ApexNonAxisChartSeries = number[];

From what I understand, with series being of type ApexAxisChartSeries, it has the property data. So I should be able to do

chart.series.map((singleSeries)=> {...})

And I should be able to access data from singleSeries, right? Vscode tells me that singleSeries is of type:

singleSeries: number | {
  name?: string | undefined;
  type?: string | undefined;
  color?: string | undefined;
  group?: string | undefined;
  data: number[][] | (number | null)[] | {
      x: any;
      y: any;
      fill?: ApexFill | undefined;
      ... 5 more ...;
      columnWidthOffset?: number | undefined;
  }[] | [...][] | [...][];
}

but the only options available to me to interact with singleSeries are toLocaleString, toString, valueOf. What's going on? How can I access data?


Solution

  • Since series is of type ApexAxisChartSeries | ApexNonAxisChartSeries, it could also be a number[]. So I think it should work if you exclude that it's not of type number[]

    Something like this might work

    chart.series.map((singleSeries)=> {
      // With this row Typescript can know that it's of type ApexAxisChartSeries inside the if statement.
      if("data" in singleSeries) {
        singleSeries.data
      }
    })
    

    OR, if you know that it's not necessary to check this, because you're in control of the data, you can assert.

    chart.series.map((singleSeries)=> {
      const singleAxisSeries = singleSeries as ApexAxisChartSeries;
      singleAxisSeries.data:
    })