TypeScript:扩展类类型无法赋值给基类类型的问题咨询
解决TypeScript中存储子类构造函数的类型不兼容问题
你遇到的问题核心是:typeof Component要求构造函数签名和抽象类完全一致,但子类Extending的构造函数参数和父类不匹配,TypeScript因此判定类型不兼容。
解决方案:定义通用的子类构造函数类型
不要直接用typeof Component作为类型,而是定义一个通用类型,只要是能生成Component实例的构造函数都能匹配。
修改后的代码如下:
abstract class Component { protected _identifier: string; protected _parent: Component | undefined; protected constructor(identifier: string, parent?: Component) { this._identifier = identifier; this._parent = parent; } } class Extending extends Component { constructor(parent?: Component) { super("hi", parent); } } // 定义通用构造函数类型:接受任意参数,返回Component实例 type ComponentConstructor = new (...args: any[]) => Component; type MapType = { component: ComponentConstructor; }; let m: MapType = { component: Extending // 此处不再报错 };
说明
ComponentConstructor类型表示所有可以通过new调用并生成Component实例的构造函数,不管子类的构造函数参数列表和父类是否一致,都能兼容。- 如果你之后需要调用
new m.component(),需要根据实际子类的构造函数传入对应参数(因为TypeScript此时无法推断具体子类的构造参数)。如果需要更精确的类型控制,可以结合泛型进一步优化,但对于存储类引用的需求,上述方案已经足够。
内容的提问来源于stack exchange,提问作者Nicolas Stadler
相关产品推荐
相关产品推荐

