首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >TypeScript: json和接口

TypeScript: json和接口
EN

Stack Overflow用户
提问于 2022-02-21 21:00:57
回答 1查看 62关注 0票数 0

我有一个元素的接口:

代码语言:javascript
复制
export interface iElm {
name?: string;
appearance?: string;
atomic_mass?: number;
boil?: number;
category?: string;
density?: number;
discovered_by?: string;
melt?: number;
molar_heat?: number;
named_by?: string;
number?: number;
period?: number;
phase?: string;
source?: string;
spectral_img?: string;
summary?: string;
symbol?: string;
xpos?: number;
ypos?: number;
shells?: number[];
electron_configuration?: string;
electron_configuration_semantic?: string;
electron_affinity?: number;
electronegativity_pauling?: number;
ionization_energies?: number[];
cpk_hex?: string;
}

我是通过使用类似于这个问题中的实用程序(json ):How to convert a json to a typescript interface?来获得这个结果的。

我使用的json是一个元素对象的对象,这些对象都有点不同,但是其中一个看起来如下:

代码语言:javascript
复制
"helium": {
"name": "Helium",
"appearance": "colorless gas, exhibiting a red-orange glow when placed in a high-voltage electric field",
"atomic_mass": 4.0026022,
"boil": 4.222,
"category": "noble gas",
"density": 0.1786,
"discovered_by": "Pierre Janssen",
"melt": 0.95,
"molar_heat": null,
"named_by": null,
"number": 2,
"period": 1,
"phase": "Gas",
"source": "https://en.wikipedia.org/wiki/Helium",
"spectral_img": "https://en.wikipedia.org/wiki/File:Helium_spectrum.jpg",
"summary": "Helium is a chemical element with symbol He and atomic number 2. It is a colorless, odorless, tasteless, non-toxic, inert, monatomic gas that heads the noble gas group in the periodic table. Its boiling and melting points are the lowest among all the elements.",
"symbol": "He",
"xpos": 18,
"ypos": 1,
"shells": [2],
"electron_configuration": "1s2",
"electron_configuration_semantic": "1s2",
"electron_affinity": -48,
"electronegativity_pauling": null,
"ionization_energies": [2372.3, 5250.5],
"cpk_hex": "d9ffff"
}

如您所见,所有东西都与iElm接口(属性是可选的,因为有一些奇怪的角案例元素)。

现在我的问题是:我有一个接收iElm的function函数组件:

代码语言:javascript
复制
const Element: FC<iElm> = (props) => {
    // some jsx stuff with the data 
}

我可以将json的属性传递给如下元素:

代码语言:javascript
复制
<Element name={table.boron.name}/>

但有什么解决办法吗?这样我就不用一个一个地检查每一处房产,然后把它复制过来了吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-02-21 21:05:48

您只需使用spread操作符将整个对象传递到:

代码语言:javascript
复制
<Element {...table.boron} />
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71212973

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档