![](/img/trans.png)
[英]TypeScript: Access nested object types and associted param types inside function body?
[英]TypeScript types for heavily nested object
我有一棵樹,我正在嘗試遞歸渲染
樹變量只是一個示例,它可能會根據應用程序獲取的數據變得更大。
即使您不知道嵌套將如何得到,我如何才能讓 TypeScript 對這棵樹上的類型感到滿意?
const tree = {
people: ['Managing Director'],
children: {
people: ['Operations Director', 'Head of Client Services'],
children: {
people: ['Senior Developer']
}
}
}
interface IList {
people: string[],
children: string[]
}
interface IData {
data: IList[]
}
const List: FC<IData> = ({ data }) => (
<ul>
{data.people.map((person) => ( <li>{person}</li> ))}
{!data.children ? null : <List data={data.children} />}
</ul>
)
function App() {
return (
<>
<List data={tree} />
</>
)
}
當我在代碼沙箱上執行此操作時,它可以工作但有警告,如果我在我的配置上執行此操作,我會得到
`Property 'people' does not exist on type 'IList[]'`
您需要將children
屬性設為可選和遞歸類型:
type Tree = {
people: Array<string>;
children?: Tree;
}
const tree: Tree = {
people: ['Managing Director'],
children: {
people: ['Operations Director', 'Head of Client Services'],
children: {
people: ['Senior Developer']
}
}
}
然后List
可以接受Tree
類型的 prop 並遞歸渲染它。
const List = ({ data }: { data: Tree }) => (
<ul>
{data.people.map((person) => (<li>{person}</li>))}
{!data.children ? null : <List data={data.children} />}
</ul>
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.