8

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?

J. Hesters
  • 13,117
  • 31
  • 133
  • 249
  • 3
    `[date: string]` allows arbitrarily many properties. It makes no sense to have that multiple times. – SLaks Oct 11 '18 at 20:21
  • 5
    It sounds like your existing `PainReport` interface already does exactly what you want. – SLaks Oct 11 '18 at 20:21
  • @SLaks You are right, wow, thank you. My questions that I guess is, how would one design an interace, that does not allow that? So an interface with just ONE key? – J. Hesters Oct 11 '18 at 20:24
  • 2
    There is no way to do that. – SLaks Oct 11 '18 at 20:24
  • @SLaks Thank you! I learned a lot. Mind copying your comments into an answer, so I can accept them? – J. Hesters Oct 11 '18 at 20:24
  • 1
    @J.Hesters, it's an old questions, yet for future readers there is a way to constrain an object to just ONE key: https://stackoverflow.com/a/60807986 – Aidin Apr 06 '20 at 13:18

2 Answers2

14

One liner using TypeScript's Record type:

type PseudoPainReportsObject = Record<string, PainData>;

Record<K, V> represents an object with any number of K type keys that map to V type values.

Leo Aso
  • 11,898
  • 3
  • 25
  • 46
2

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

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

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964