【问题标题】:How to extend a recursive typescript interface?如何扩展递归打字稿接口?
【发布时间】:2022-01-20 06:25:26
【问题描述】:

我有一个递归接口,如下所示:

interface TreeNode {
  id: string
  children: TreeNode[]
}

我想像这样扩展TreeNode

interface TreeNodeWithMorePros extends TreeNode{
  moreProps: any[]
}

但这还不够,因为root 可以拥有moreProps,但孩子们不能。

const tree: TreeNodeWithMorePros = {
  id: 'root', 
  moreProps: [], 
  children: [
    {
      id: 'child', 
      children: [],
      // here I cannot use moreProps
    }
  ]
}

如何正确扩展TreeNode 接口?

【问题讨论】:

    标签: typescript types interface typescript-typings typescript-generics


    【解决方案1】:

    其实我刚刚找到了解决办法

    有一个多态类型this可以使用:

    interface TreeNode {
      id: string
      children: this[]
    }
    
    interface TreeNodeWithMorePros extends TreeNode{
      moreProps: any[]
    }
    
    const tree: TreeNodeWithMorePros = {
      id: 'something',
      moreProps: [],
      children: [
        {
          id: 'child',
          children: [],
          moreProps: []
        }
      ]
    }
    

    现在可以正常使用了

    【讨论】:

      猜你喜欢
      • 2019-05-04
      • 2019-01-20
      • 1970-01-01
      • 1970-01-01
      • 2019-01-06
      • 1970-01-01
      • 1970-01-01
      • 2021-09-20
      相关资源
      最近更新 更多