简体   繁体   English

TypeScript:json和接口

[英]TypeScript: json and interface

I have an interface for an element:我有一个元素的接口:

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;
}

I got this by using a utility similar to the one in this question (json to ts): How to convert a json to a typescript interface?我通过使用类似于这个问题(json 到 ts)中的实用程序得到了这个: How to convert a json to a typescript interface?

The json that I'm using is an object of element object that are all a bit different but one looks like this:我正在使用的 json 是元素 object 的 object,它们都有点不同,但看起来像这样:

"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"
}

As you can see everything lines up with the iElm interface (properties are optional because there are some weird corner case elements)正如您所看到的,所有内容都与 iElm 界面一致(属性是可选的,因为有一些奇怪的极端案例元素)

Now here's my problem: I have a React function component that takes in an iElm:现在这是我的问题:我有一个接受 iElm 的 React function 组件:

const Element: FC<iElm> = (props) => {
    // some jsx stuff with the data 
}

I can pass properties of the json to Element like so:我可以像这样将 json 的属性传递给 Element:

<Element name={table.boron.name}/>

But is there some workaround so that I don't have to go through every property one by one and copy it over?但是有没有一些解决方法,这样我就不必 go 一个一个地遍历每个属性并将其复制过来?

You can simply use the spread operator to pass the entire object in:您可以简单地使用扩展运算符将整个 object 传递到:

<Element {...table.boron} />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM