[英]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 .我正在使用 Redux 和Normalizr在 TypeScript 中构建一个 React Native 应用程序。 So I will have noramlized state.
所以我会有规范化的状态。
I have four interfaces: Emotion
, Need
, PainData
and PainReport
:我有四个接口:
Emotion
、 Need
、 PainData
和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):现在我想创建一个接口,它不是一个数组,而是一个允许多个这样的 PainReports 的对象(伪代码):
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.我想将它用于规范化状态,就像使用 Normalizr 时一样。
How would one do such a type or interface?如何做这样的类型或接口?
One liner using TypeScript's Record
type:使用 TypeScript 的
Record
类型的一个班轮:
type PseudoPainReportsObject = Record<string, PainData>;
Record<K, V>
represents an object with any number of K
type keys that map to V
type values. Record<K, V>
表示具有任意数量的K
类型键的对象,这些键映射到V
类型值。
[date: string]
allows arbitrarily many properties; [date: string]
允许任意多个属性; PainReport
does exactly what you want. PainReport
正是您想要的。
There is no way to constrain it to only one property.没有办法将它限制为只有一个属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.