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?
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.
Typescript allows an interface to inherit from multiple interfaces.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With