重嵌套对象的 TypeScript 类型

Álv*_*aro 4 typescript reactjs

我有一棵树,我正试图递归渲染

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

即使我不知道嵌套将如何获得,我如何才能让 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} />
    </>
  )
}

Run Code Online (Sandbox Code Playgroud)

当我在代码和盒子上做它时,它可以工作但有警告,如果我在我的配置上做我得到

`Property 'people' does not exist on type 'IList[]'`
Run Code Online (Sandbox Code Playgroud)

例子

Cer*_*nce 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']
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

然后List可以接受类型的道具Tree并递归渲染它。

const List = ({ data }: { data: Tree }) => (
    <ul>
        {data.people.map((person) => (<li>{person}</li>))}
        {!data.children ? null : <List data={data.children} />}
    </ul>
)
Run Code Online (Sandbox Code Playgroud)

  • 我会删除“FC”、“IList”和“IList”类型,IMO 它们没有做任何对您有用的事情。只需使用一个“Tree”类型作为道具即可。 (2认同)