[英]How to declare string > string > number structure in TypeScript?
I need to declare a useState, but I do not clealy understand TypeScript.我需要声明一个 useState,但我不太了解 TypeScript。 What should I write in place of
XXXXXX
.我应该写什么来代替
XXXXXX
。 I have a strict JSON with string > string > number structure and I will populate selectedLayoutItemIds
from it.我有一个严格的 JSON 字符串 > 字符串 > 数字结构,我将从它填充
selectedLayoutItemIds
。 Top level id is called eventTimeId
, 2nd level I would call layoutItemId
, 3rd level count
.顶级 id 称为
eventTimeId
,第二级我称为layoutItemId
,第三级count
。 Would you help a bit?你能帮点忙吗?
const [selectedLayoutItemIds, setSelectedLayoutItemIds] = useState<
{ [eventTimeId: string]: XXXXXX } | undefined
>();
You only have to describe the structure of the data as you would do in a regular json and the 1st & 2nd level keys will be treated as strings:您只需要像在常规 json 中所做的那样描述数据的结构,并且 1 级和 2 级键将被视为字符串:
interface LayoutItemIds {
eventTimeId: {
layoutItemId: {
count: number;
}
}
}
const [selectedLayoutItemIds, setSelectedLayoutItemIds] = useState<LayoutItemIds | undefined>();
Here is a playground to see it in action.这是一个可以看到它运行的操场。
Finally I declared a new interface:最后我声明了一个新接口:
export type LayoutItemIdsWithAvailability = {
[layoutItemId: string]: number;
};
and used here:并在这里使用:
const [selectedLayoutItemIds, setSelectedLayoutItemIds] = useState<
{ [eventTimeId: string]: LayoutItemIdsWithAvailability } | undefined
>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.