我得到了一棵树,我正试图以递归方式呈现
树变量只是一个例子,它可能会变得更大,这取决于应用程序获得的数据。
我如何才能让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} />
</>
)
}当我在codesandbox上做这件事时,它是有效的,但有警告,如果我在我的配置上做,我会得到
`Property 'people' does not exist on type 'IList[]'`发布于 2021-01-31 00:48:31
您需要将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类型的属性并递归呈现它。
const List = ({ data }: { data: Tree }) => (
<ul>
{data.people.map((person) => (<li>{person}</li>))}
{!data.children ? null : <List data={data.children} />}
</ul>
)https://stackoverflow.com/questions/65970528
复制相似问题