为对象的所有属性定义模式

时间:2020-02-10 23:49:54

标签: javascript typescript

我在应用程序中定义了一个Product接口,如下所示:

export interface Product {
  // other properties here
  datesForComparison?: {};
}

基本上我希望datesForComparison的结构如下

{
  "2020-01-01": {
    price: 10,
    unitPrice: 5,
    percent: 5
  },
  "2020-01-02": {
    price: 4,
    unitPrice: 2,
    percent: -1
  },
  ...
}

是否可以在Typescript中定义属性的这种重复模式? 谢谢!

1 个答案:

答案 0 :(得分:1)

我认为您正在寻找Index Signature

export interface Product {
  datesForComparison?: {
    [date: string]: {
      price: number;
      unitPrice: number;
      percent: number;
    }
  }
}