网站搜索

类型 - 扩展和修改嵌套的 TypeScript 接口


我如何向 datasets[0] 中的对象添加内容?

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

export interface PieCharState extends ChartState {}

我想补充的是:

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

** 我知道这不是应该做的方式(指定索引等),但那是目标。谢谢你的帮助!

答案#1

您可以通过像这样引用并扩展您的数据集类型来定义新的类型:

首先,提取数据集类型:

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

然后为条形图定义你的新数据集类型:

type _barChartDataSetType = _dataSetType & {
   barThickness: number;
}

最后定义你的 BarChartState:

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

这允许你按预期使用它:

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

完整的 TypeScript Playground 示例