簡體   English   中英

TypeScript:json和接口

[英]TypeScript: json and interface

我有一個元素的接口:

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 到 ts)中的實用程序得到了這個: How to convert a json to a typescript interface?

我正在使用的 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"
}

正如您所看到的,所有內容都與 iElm 界面一致(屬性是可選的,因為有一些奇怪的極端案例元素)

現在這是我的問題:我有一個接受 iElm 的 React function 組件:

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

我可以像這樣將 json 的屬性傳遞給 Element:

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

但是有沒有一些解決方法,這樣我就不必 go 一個一個地遍歷每個屬性並將其復制過來?

您可以簡單地使用擴展運算符將整個 object 傳遞到:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM