我应该在哪个文件中放置 returns 新子类的开关函数

In which file should i put a switch function that returns new subclass

我有一个parentclass

export class Component{

}

还有很多 children classes

export class ComponentOne extends Component{

}
export class ComponentTwo extends Component{

}

我想在组件中创建一个函数,该函数 returns 基于数据 class 的正确类型

parseComponentDatabase(databaseObject){
    switch(databaseObject.type){
        case "One": 
             return new ComponentOne(databaseObject)
        case "Two":
             return new ComponentTwo(databaseObject)
    }
}

我想将该函数放在 Component 中,但这最终导致循环依赖,因为这使得 Component 导入它的 children,并且它的 children 已经导入它。我的打字稿项目中禁止循环依赖。

我的问题是,我必须把这个函数放在哪个文件中?

您需要使用工厂来实例化您的对象,而不是在组件中执行此操作class,请参阅工厂模式文档。