【发布时间】:2021-12-15 17:50:08
【问题描述】:
我有一个类层次结构,例如扩展父级的Parent、Child1、Child2 等。
Parent 存储一组子项,我需要在 Parent 中导入 Child1 和 Child2。
这显然会导致循环依赖并在尝试创建 Child1 或 Child 2 时抛出以下错误:
TypeError: Super expression must either be null or a function
有什么办法可以解决这个问题?
例如,考虑以下结构:
parent.js
export default class Parent {
itemArray = []
}
child1.js
import Parent from "./parent.js"
export default class Child1 extends Parent {
}
child2.js
import Parent from "./parent.js"
export default class Child2 extends Parent {
}
itemArray 递归存储Child1 或Child2
现在我需要对 itemArray 进行类型注释,以便 parent.js 如下所示:
parent.js
import Child1 from "./child1"
import Child2 from "./child2"
export default class Parent {
@Types(() => [Child1, Child2])
itemArray = []
}
当最终对象是从普通对象构造时,此注释允许为数组中的每个项目分配正确的类。但这就是细节。问题是:
如何允许这样的结构不破坏整个层次结构?
【问题讨论】:
标签: javascript