Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 680
J. Hesters Avatar asked Oct 11 '18 20:10

J. Hesters


People also ask

How do I create an interface object in TypeScript?

To create an object based on an interface, declare the object's type to be the interface, e.g. const obj1: Employee = {} . The object has to conform to the property names and the type of the values in the interface, otherwise the type checker throws an error.

Can TypeScript implement multiple interfaces?

Typescript allows an interface to inherit from multiple interfaces.

How do you define a key of an object in TypeScript?

Use the keyof typeof syntax to create a type from an object's keys, e.g. type Keys = keyof typeof person . The keyof typeof syntax returns a type that represents all of the object's keys as strings.

What is the difference between the keywords interface and type in TypeScript?

The typescript type supports only the data types and not the use of an object. The typescript interface supports the use of the object. Type keyword when used for declaring two different types where the variable names declared are the same then the typescript compiler will throw an error.


1 Answers

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.

like image 143
Leo Aso Avatar answered Oct 24 '22 05:10

Leo Aso