JSON对象到React中的typescript类

huangapple go评论93阅读模式
英文:

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&lt;string,Inner[]&gt;
// or
type Thing = {
   [K: string]: Inner[]
}

you can learn more at the docs

huangapple
  • 本文由 发表于 2023年6月5日 19:08:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76405830.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定