英文:
How to i type this object from api response?
问题
{
"_metadata": {
"uid": "someuid"
},
"reference": [
{
"locale": "en-us",
"close_icon_size": "",
"icons": {
"default": {
"uid": "someuid",
"dimension": {
"height": 48,
"width": 48
},
"title": "bell-icon-new.svg",
"parent_uid": null,
"is_dir": false,
"url": "https://url.com"
},
"link_text": "Text text tex",
"styles": {
"font_size": "24px",
"width": "1400px",
"font_color": {
"colorTheme": "custom",
"height": "75px",
"link_text_size": "16px",
"background_color": {
"colorTheme": "custom",
"font_family": "Arial"
},
"title": "Text",
"_content_type_uid": "text text text"
}
}
}
}
]
}
英文:
{
"_metadata": {
"uid": "someuid"
},
"reference": [
{
"locale": "en-us",
... bunch of similar key:value
"close_icon_size": "",
"icons": {
"default": {
"uid": "someuid",
... bunch of similar key:value
"dimension": {
"height": 48,
"width": 48
},
"title": "bell-icon-new.svg",
"parent_uid": null,
"is_dir": false,
"url": "https://url.com"
},
... bunch of similar repeated object
},
"link_text": "Text text tex",
"styles": {
"font_size": "24px",
"width": "1400px",
"font_color": {
"colorTheme": "custom",
... bunch of similar key:value
},
"height": "75px",
"link_text_size": "16px",
"background_color": {
"colorTheme": "custom",
... bunch of similar key:value
},
"font_family": "Arial",
... bunch of similar key:value
},
"title": "Text",
"_content_type_uid": "text text text"
}
]
}
I am totally new to TypeScript. How do i type this kinds of objects? We have bunch of them which is slowing down my development?
I am planning to give type to each key:value but that will be exhausting job to do for large objects like this.
Any help would be apprerciated.
Thank you
答案1
得分: 3
只需将此对象分配给一个const并将其悬停在您的IDE中(至少在VS Code中有效)。
甚至不必指定此类型,您可以直接访问元素:
import React from 'react';
export function App(props) {
const myVar = "yourJSON";
return (
<div>
<h1>{myVar.reference.locale}</h1>
</div>
);
}
Typescript需要在动态对象上指定类型
- 如果它来自一个网络服务,只需使用像openapi-typescript这样的工具从swagger生成类型
- 如果它来自一个库,请检查是否有相应的@type包。
- 而在最坏的情况下,只需复制粘贴在IDE中悬停变量时显示的类型
英文:
Just assign this object on a const and hover it in your IDE (at least works in VS Code).
You don't even have to specify this type, you can directly access the elements :
import React from 'react';
export function App(props) {
const myVar = "yourJSON"
return (
<div>
<h1>{myVar.reference.locale}</h1>
</div>
);
}
Typescript needs type on dynamic objects
- If it comes from a webservice, just use tools like openapi-typescript to generate the types from a swagger
- If it comes from a library, check if there's a corresponding @type package.
- And in the worst case, just copy paste the type displayed when you hover your variable in your IDE
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论