[英]TypeScript types for heavily nested object
I got a tree I am trying to render recursively我有一棵树,我正在尝试递归渲染
The tree variable is just an example it could grow much bigger depending on the data the app gets.树变量只是一个示例,它可能会根据应用程序获取的数据变得更大。
How can I keep TypeScript happy about the types on this tree even thou I don't know how nested is going to get?即使您不知道嵌套将如何得到,我如何才能让 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} />
</>
)
}
When I do it on codesandbox it works but with warnings, If I do it on my config I get当我在代码沙箱上执行此操作时,它可以工作但有警告,如果我在我的配置上执行此操作,我会得到
`Property 'people' does not exist on type 'IList[]'`
You need to make the children
property optional and a recursive type:您需要将
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']
}
}
}
Then List
can accept a prop of type Tree
and recursively render it.然后
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.