英文:
JSON Object to typescript class in react
问题
我正在努力将JSON转换为TypeScript接口,但无法进行映射。
我有以下格式的JSON字符串,允许数组
{
"abc": [
{"key": "a", "value": "a"},
{"key": "b", "value": "b"},
{"key": "c", "value": "c"}
],
"cdf": [
{"key": "a", "value": "a"},
{"key": "b", "value": "b"},
{"key": "c", "value": "c"}
]
}
我想在React中为它定义一个类,但遇到了问题。请问有谁可以帮忙为上面的JSON声明TypeScript类。
编辑:
请注意,键不是静态的。
提前感谢您的帮助。
英文:
I am working on converting the JSON to typescript interface and unbale to map the same.
I have the below format JSON string which allows array
{
"abc": [
{"key": "a", "value": "a"},
{"key": "b", "value": "b"},
{"key": "c", "value": "c"}
],
"cdf": [
{"key": "a", "value": "a"},
{"key": "b", "value": "b"},
{"key": "c", "value": "c"}
],
}
I would like to define the class for it in the react but facing issues. Could any one please help to declare the typescript class for the above JSON.
Edited:
Please note keys are not static
Thanks in advance
答案1
得分: 2
type Inner = { key: string, value: string }
type Thing = {
abc: Inner[],
cdf: Inner[]
}
对于不是静态键的情况:
type Thing = Record<string, Inner[]>
// 或者
type Thing = {
[K: string]: Inner[]
}
你可以在文档中了解更多信息。
<details>
<summary>英文:</summary>
```typescript
type Inner = {key: string, value: string}
type Thing = {
abc: Inner[],
cdf: Inner[]
}
for not static keys
type Thing = Record<string,Inner[]>
// or
type Thing = {
[K: string]: Inner[]
}
you can learn more at the docs
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论