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

2

12

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?

Gynaeceum answered 11/10, 2018 at 20:19 Comment(6)
[date: string] allows arbitrarily many properties. It makes no sense to have that multiple times.Sylvie
It sounds like your existing PainReport interface already does exactly what you want.Sylvie
@Sylvie 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?Gynaeceum
There is no way to do that.Sylvie
@Sylvie Thank you! I learned a lot. Mind copying your comments into an answer, so I can accept them?Gynaeceum
@J.Hesters, it's an old questions, yet for future readers there is a way to constrain an object to just ONE key: stackoverflow.com/a/60807986Pitiable
S
4

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

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

Sylvie answered 11/10, 2018 at 21:21 Comment(2)
There is a way to constrain an object to have only one property. It is not trivial though: stackoverflow.com/a/60807986Pitiable
Downvote: The second part of the answer is wrong. (See comment by Aidin)Stepdaughter
S
21

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.

Spiritism answered 24/4, 2020 at 14:29 Comment(0)
S
4

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

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

Sylvie answered 11/10, 2018 at 21:21 Comment(2)
There is a way to constrain an object to have only one property. It is not trivial though: stackoverflow.com/a/60807986Pitiable
Downvote: The second part of the answer is wrong. (See comment by Aidin)Stepdaughter

© 2022 - 2024 — McMap. All rights reserved.