英文:
Why typeof does not check inheritance of class?
问题
如何使示例工作?为什么在这个示例中不能使用 typeof,以及它可以被替代为什么?
abstract class Check {
constructor(public field: number) {
}
}
class Check1 extends Check {
field1: number;
constructor(field: number, field1:number) {
super(field);
this.field1 = field1;
}
}
abstract class CheckUser {
abstract getConstructor(): typeof Check;
}
class Check1User extends CheckUser {
getConstructor(): typeof Check {
return Check1;
}
}
英文:
how to make an example work? Why i can not use typeof in this example and what can it be replaced with?
abstract class Check {
constructor(public field: number) {
}
}
class Check1 extends Check {
field1: number;
constructor(field: number, field1:number) {
super(field);
this.field1 = field1;
}
}
abstract class CheckUser {
abstract getConstructor(): typeof Check;
}
class Check1User extends CheckUser{
getConstructor(): typeof Check {
return Check1;
}
}
答案1
得分: 2
Returning typeof Check
意味着你必须返回一个具有 Check
的所有静态成员但也有与 Check
构造函数相同参数的类型。由于 Check1
的构造函数有额外的参数,所以它不能赋值给 Check
构造函数的类型。
你可以从 Checked1
中移除额外的参数,然后赋值就会起作用。
你还可以更改基类以接受泛型类型参数,该参数必须是返回 Checked
构造函数的构造函数:
abstract class CheckUser<T extends new (...a: never[]) => Check> {
abstract getConstructor(): T;
}
class Check1User extends CheckUser<typeof Check1> {
getConstructor() {
return Check1;
}
}
可能还有其他选项,但这取决于你打算在之后对 getConstructor
做什么。
英文:
Returning typeof Check
means you have to return a type that has all the statics of Check
but also have a constructor with the same arguments as that of Check
. Since Check1
has another argument to it's constructor it will not be assignable to the type of the Check
constructor.
You can remove the extra parameter from Checked1
and the assignment will work (ex)
You could also change the base class to take a generic type argument that must be a constructor that returns Checked
:
abstract class CheckUser<T extends new (...a: never[]) => Check> {
abstract getConstructor(): T;
}
class Check1User extends CheckUser<typeof Check1>{
getConstructor() {
return Check1;
}
}
There might be other options as well but it depends what you want to do with getConstructor
afterwards.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论