gpt4 book ai didi

inheritance - Typescript 不允许具有不同构造函数签名的类的 typeof 继承

转载 作者:搜寻专家 更新时间:2023-10-30 20:59:21 24 4
gpt4 key购买 nike

我正在实现一个 commandBus,我想用命令处理程序注册命令类型,以将传入的命令映射到正确的命令处理程序。我传递了一个命令构造函数来映射到一个处理程序构造函数,就像这样 register(handler : typeof Handler, command : typeof Command)。但我不断收到编译错误。

我终于查出原因了。在 typescript 中,您不能定义参数 arg typeof X 并传入构造函数 Y,事件 if 'Y extends X构造函数必须具有相同的签名

检查该片段。在底部,即使 commandBus.register(Object) 也不会抛出编译错误。

class BaseClass{}
class DerivedClass extends BaseClass{
constructor(b : number) {
super();
}
}
class AnotherClass extends BaseClass{
constructor(){
super();
}
}
class CommandBus {
register(handler : typeof BaseClass) {}
}
var commandBus = new CommandBus();
commandBus.register(DerivedClass); // Argument of type 'typeof DerivedClass' is not assignable to parameter of type 'typeof BaseClass'.
commandBus.register(AnotherClass); // Compiles
commandBus.register(Function); // Compiles
commandBus.register(Object); // Compiles

我让它工作的唯一方法是添加一个重载构造函数签名

class DerivedClass extends BaseClass{
constructor(b? : any);
constructor(b : number) {
super();
}
}

但是是我还是这太丑了?

任何人都可以指出如何消除这些编译器错误,而无需到处添加无用的重载签名的肮脏技巧吗?

最佳答案

你在这里真正想说的是你想要一个构造函数用于一个BaseClass,它接受任意数量的参数。你可以这样写:

class CommandBus {
register(handler: new(...args: any[]) => BaseClass) {}
}

请注意,错误是 100% 正确的。如果你写了

class CommandBus {
register(handler : typeof BaseClass) {
var x = new handler();
}
}
var c = new CommandBus();
c.register(DerivedClass);

您将向 DerivedClass 构造函数传递零参数。


这些行在这里

commandBus.register(Function); // Compiles
commandBus.register(Object); // Compiles

只编译因为 BaseClass 没有成员(记住,TypeScript 使用结构类型系统,所以空类型可以任何类型分配!)。如果您将任何不在 FunctionObject 中的属性或方法添加到 BaseClass,这些行将成为错误。

关于inheritance - Typescript 不允许具有不同构造函数签名的类的 typeof 继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33442687/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com