小编jdl*_*lin的帖子

TypeScript 接口可以被识别为它们继承的接口吗?

我有一个 TypeScript 接口,可以通过许多其他接口进行扩展。例如,调用它Parent并说 2 个接口扩展Parent并称为ChildAChildB。事实上,还有更多的孩子继承了Parent

interface Parent {
  sharedProp: string;
}

interface ChildA extends Parent {
  uniqueChildAProp: string;
}

interface ChildB extends Parent {
  uniqueChildBProp: string;
}
Run Code Online (Sandbox Code Playgroud)

有没有办法让我拥有另一个Grandparent定义类似于如下的接口:

interface Grandparent {
  children: Parent[];
}
Run Code Online (Sandbox Code Playgroud)

数组中的元素children可以是ChildAor ChildB(或扩展的任何其他接口Parent)?

这将是一个有效的Grandparent

const concrete: Grandparent = {
  children: [
    {
      sharedProp: 'fooA',
      uniqueChildAProp: 'barA'
    },
    {
      sharedProp: 'foo',
      uniqueChildBProp: 'barB'
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

我想避免合并类型, …

javascript inheritance interface typescript

3
推荐指数
1
解决办法
2077
查看次数

标签 统计

inheritance ×1

interface ×1

javascript ×1

typescript ×1