[英]How to create a type of an object, which has a dynamic number of keys, depending on the values of a string array, which is in the same object?
I'm working with Magnolia headless CMS and I'm receiving the following response:我正在使用 Magnolia headless CMS,我收到了以下回复:
const myResponseObject = {
"@name": "slides",
"@path": "/home/main/00/slides",
"@id": "db9bffe6-6425-4601-8005-65fd52500caf",
"@nodeType": "mgnl:contentNode",
"mgnl:createdBy": "superuser",
"mgnl:lastModified": "2022-12-15T09:38:01.993+01:00",
"mgnl:created": "2022-12-15T09:38:01.993+01:00",
"mgnl:lastModifiedBy": "superuser",
"slides0": {
"@name": "slides0",
"@path": "/home/main/00/slides/slides0",
"@id": "faf338c1-8e82-4cc2-aa97-0cd6f22047a8",
"@nodeType": "mgnl:contentNode",
"mgnl:createdBy": "superuser",
"title": "The title of the slide",
"mgnl:lastModified": "2022-12-15T09:38:01.994+01:00",
"subtitle": "The subtitle of the slide",
"mgnl:created": "2022-12-15T09:38:01.994+01:00",
"mgnl:lastModifiedBy": "superuser",
"@nodes": []
},
"slides1": {
"@name": "slides1",
"@path": "/home/main/00/slides/slides1",
"@id": "1c3098c8-35be-4b3a-b23c-5af2a25dffe5",
"@nodeType": "mgnl:contentNode",
"mgnl:createdBy": "superuser",
"title": "The title of slide 2",
"mgnl:lastModified": "2022-12-15T09:38:01.994+01:00",
"subtitle": "The subtitle of slide 2",
"mgnl:created": "2022-12-15T09:38:01.994+01:00",
"mgnl:lastModifiedBy": "superuser",
"@nodes": []
},
"@nodes": [
"slides0",
"slides1"
]
}
Depending on how many slides I add in Magnolia the @nodes array has more entries and for each entry is an additional entry in my object, with the value of the array item as key.根据我在 Magnolia 中添加的幻灯片数量,@nodes 数组有更多条目,并且每个条目都是我对象中的一个附加条目,数组项的值作为键。
So how can I type this properly in TypeScript?那么如何在 TypeScript 中正确输入呢?
Alreade tried something like this, but that's not related to the @nodes array:已经尝试过类似的方法,但这与@nodes 数组无关:
IMagnoliaBasis in this example contains all the fields which are the same for all components, like @name, @id, mgnl:created, etc.此示例中的 IMagnoliaBasis 包含所有组件都相同的所有字段,如 @name、@id、mgnl:created 等。
type MyResponse = Record<string, string[]> & {
[key in keyof string[]]: IHomeHeroSlide;
} & IMagnoliaBasis;
interface IHomeHeroSlide extends IMagnoliaBasis {
title: string;
subtitle: string;
}
Is this what you want?这是你想要的吗?
const slides = ["slides0", "slides1"] as const
type MyResponse = {
[K in (typeof slides)[number]]: IMongoliaBasis
} & {
"@nodes": typeof slides
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.