2

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 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.