typescript - Why typeof does not check inheritance of class?
问题描述
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;
}
}
解决方案
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.
推荐阅读
- php - 具有不同金额的条纹的定期付款
- react-native - 如何在 RN 中将反向 FlatList 的加载指示器保持在顶部
- angular - 为什么必须为每个惰性模块提供 HTTP_INTERCEPTORS
- android - 为什么在 Android Pie 中创建数据库时需要 close()?
- django - 如何在 Django 中访问未定义的数据库?
- c++ - 如何在多个进程中使用 Valgrind?
- php - 在 Laravel 中注册新的全局作用域
- java - Ejb不会初始化实体管理器
- amazon-web-services - Pyspark - 从 EMR 上的弹性搜索集群中读取数据
- ios - 应用程序强制退出时未收到丰富的通知