TypeScript:如何为具有多个相同类型的键和相同类型的值的对象创建接口?

J. *_*ers 10 typescript redux normalizr typescript-typings typescript-types

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

我有四个接口:EmotionNeed和:PainDataPainReport

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
}
Run Code Online (Sandbox Code Playgroud)

现在我想创建一个不是数组的接口,而是一个允许多个 PainReport 的对象,如下所示(伪代码):

export interface PseudoPainReportsObject {
  [date: string]: PainData,
  [date: string]: PainData,
  [date: string]: PainData,
  // ... dynamically have as many as I'd like. Maybe 1, maybe 100
}
Run Code Online (Sandbox Code Playgroud)

我想将其用于标准化状态,就像使用 Normalizr 时获得的那样。

如何创建这样的类型或接口?

Leo*_*Aso 18

使用 TypeScript 的Record类型的一个衬垫:

type PseudoPainReportsObject = Record<string, PainData>;
Run Code Online (Sandbox Code Playgroud)

Record<K, V>K表示具有任意数量的映射到类型值的类型键的对象V


SLa*_*aks 4

[date: string]允许任意多个属性;PainReport正是你想要的。

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

  • 有一种方法可以限制对象仅具有一个属性。但这并不是微不足道的:/sf/answers/4256559051/ (2认同)