【问题标题】:TypeScript: How to create an interface for an object with many keys of the same type and values of the same type?TypeScript:如何为具有许多相同类型的键和相同类型的值的对象创建接口?
【发布时间】:2019-03-17 00:32:59
【问题描述】:

我正在使用 Redux 和 Normalizr 在 TypeScript 中构建一个 React Native 应用程序。所以我会有规范化的状态。

我有四个接口:EmotionNeedPainDataPainReport

export interface Emotion {
  name: string;
  chosen: boolean;
  rating: number;
}

export interface Need {
  name: string;
  rating: number;
}

export interface PainData {
  note: string;
  emotions: Emotion[];
  needs: Need[];
  date: Date;
}

export interface PainReport {
  [date: string]: PainData
}

现在我想创建一个不是数组的接口,而是一个对象,它允许像这样的多个 PainReports(伪代码):

export interface PseudoPainReportsObject {
  [date: string]: PainData,
  [date: string]: PainData,
  [date: string]: PainData,
  // ... dynamically have as many as I'd like. Maybe 1, maybe 100
}

我想将它用于标准化状态,就像您在使用 Normalizr 时一样。

如何做这样的类型或接口?

【问题讨论】:

  • [date: string] 允许任意多个属性。多次这样做是没有意义的。
  • 听起来您现有的PainReport 界面已经完全符合您的要求。
  • @SLaks 你说得对,哇,谢谢。我猜我的问题是,如何设计一个不允许这样做的交互?那么只有一个键的界面?
  • 没有办法。
  • @J.Hesters,这是一个老问题,但对于未来的读者来说,有一种方法可以将对象限制为一个键:stackoverflow.com/a/60807986

标签: typescript redux typescript-typings normalizr typescript-types


【解决方案1】:

[date: string] 允许任意多个属性; PainReport 完全符合您的要求。

没有办法将其限制为只有一个属性。

【讨论】:

  • 有一种方法可以限制一个对象只有一个属性。但这并非微不足道:stackoverflow.com/a/60807986
  • 投反对票:答案的第二部分是错误的。 (见艾丁的评论)
【解决方案2】:

一个使用 TypeScript 的 Record 类型的划线器:

type PseudoPainReportsObject = Record<string, PainData>;

Record&lt;K, V&gt; 表示具有任意数量的 K 类型键映射到 V 类型值的对象。

【讨论】:

    猜你喜欢
    • 2022-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-25
    相关资源
    最近更新 更多