【问题标题】:TypeScript: how do I type-annotate an object with attributes all of the same type? (Object<type> Array<type>)TypeScript:如何使用所有相同类型的属性对对象进行类型注释? (对象<类型> 数组<类型>)
【发布时间】:2020-10-03 19:35:54
【问题描述】:

我想使用 TypeScript 类型强类型化我的 festivals 对象。每个属性的类型始终为IFestival。我不想以我拥有的方式定义IFestivals,因为还有大约 20 个属性。有没有办法告诉 TypeScript 与对象关联的每个属性都属于同一类型?有点像你可以用type IFestivals = Array&lt;IFestival&gt; 代替IFestivals = Object&lt;IFestival&gt; 吗?

代码如下:

interface IFestival {
  name: string;
  festival?: boolean;
  favourite?: boolean;
}

// I do not want to define it this way as there are 25+ attributes like this in reality...
interface IFestivals extends Object {
  BESTIVAL: IFestival;
  GLASTONBURY: IFestival;
  LOVEBOX: IFestival;
  MIGHTY_HOOPLA: IFestival;
  PARKLIFE: IFestival;
}

const festivals: IFestivals = {
  BESTIVAL: { name: "Bestival", festival: true },
  GLASTONBURY: { name: "Glastonbury", festival: true, favourite: true },
  LOVEBOX: { name: "Lovebox", festival: true },
  MIGHTY_HOOPLA: { name: "Mighty Hoopla", festival: true },
  PARKLIFE: { name: "Parklife", festival: true }
};

【问题讨论】:

    标签: typescript object types enums


    【解决方案1】:

    除非您想使用 indexed type(或 Map&lt;string,IFestival&gt;),它不控制属性的名称(您只能按 string | numbernumber 进行索引,而不是枚举或类似名称) :

    type IFestivals = {[name: string]: IFestival};
    

    ...那么你将要写 something 25 次。这真的没什么大不了的。

    最好的办法是做你已经做过的事情,尽管没有隐含的extends Object

    interface IFestivals {
      BESTIVAL: IFestival;
      GLASTONBURY: IFestival;
      LOVEBOX: IFestival;
      MIGHTY_HOOPLA: IFestival;
      PARKLIFE: IFestival;
      // ...
    }
    

    但是,如果您需要在一个接口中使用一种类型而在另一个接口中使用另一种类型的这 25 个属性,则可以使用泛型:

    interface Samey<T> {
      BESTIVAL: T;
      GLASTONBURY: T;
      LOVEBOX: T;
      MIGHTY_HOOPLA: T;
      PARKLIFE: T;
      // ...
    }
    type IFestivals = Samey<IFestival>;
    type ISomethingElses = Samey<ISomethingElse>;
    

    不过,没有理由为单个界面这样做。

    【讨论】:

      猜你喜欢
      • 2023-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-28
      • 1970-01-01
      • 2023-04-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多