extend and modify nested typescript interface

Viewed 337

how can I add to the object in datasets[0]?


interface ChartState {
    labels: string[];
    datasets: [
        {
            label: string;
            backgroundColor: string[] | string;
            hoverBackgroundColor: string[] | string;
            data:  (string|number)[];
        }
    ];
}

export interface PieCharState extends ChartState {}

what I would like to add:

export interface BarCharState extends ChartState{
  datasets[0].barThickness: number;
}

** I know thats not how it spouse to be done (specifing the index etc) but thats the goal. Thanks for the help!

1 Answers

You can define your new type by referencing and extending your dataset type like this:

First, extract the dataset type:

type _dataSetType = ChartState['datasets'][0];

then define your new dataset type for the barchart:

type _barChartDataSetType = _dataSetType & {
   barThickness: number;
}

Finally define your BarChartState:

export type BarCharState = ChartState & {
  datasets: Array<_barChartDataSetType>
}

which allows you do use it as expected:

const test: BarCharState = {
   labels: ['foo', 'bar'],
   datasets: [
      {
         label: 'foo',
         backgroundColor: '#fefefe',
         hoverBackgroundColor: '#ffffff',
         data: ['a', 'b'],
         barThickness: 3,
      },
   ]
}

Full Typescript Playground Example

Related