簡體   English   中英

TypeScript 類型用於重度嵌套 object

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM