重嵌套对象的 TypeScript 类型

时间:2021-01-30 16:45:15

标签: reactjs typescript

我得到了一棵树,我正在尝试递归渲染

树变量只是一个例子,它可以根据应用获取的数据变得更大。

即使我不知道嵌套将如何获得,我如何才能让 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[]'`

EXAMPLE

1 个答案:

答案 0 :(得分:5)

您需要将 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>
)