Search code examples
typescriptreduxtypescript-typingsnormalizrtypescript-types

TypeScript: How to create an interface for an object with many keys of the same type and values of the same type?


I'm building a React Native app in TypeScript with Redux and Normalizr. So I will have noramlized state.

I have four interfaces: Emotion, Need, PainData and PainReport:

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
}

Now I would like to create an interface that is not an array, but an object an allows several PainReports like this (pseudo code):

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

I want to use this for normalized state like you get when using Normalizr.

How would one do such a type or interface?


Solution

  • [date: string] allows arbitrarily many properties; PainReport does exactly what you want.

    There is no way to constrain it to only one property.