在TypeScript中,我可以将变量的类型定义为类的类型.例如:
class MyClass { ... }
let myVar: typeof MyClass = MyClass;
Run Code Online (Sandbox Code Playgroud)
现在我想将它与泛型类一起使用,如下所示:
class MyManager<T> {
constructor(cls: typeof T) { ... }
/* some other methods, which uses instances of T */
}
let test = new MyManager(MyClass); /* <MyClass> should be implied by the parameter */
Run Code Online (Sandbox Code Playgroud)
所以,我想给我的经理类另一个类(它的构造函数),因为管理器需要检索与该类关联的静态信息.
在编译我的代码时,它说它找不到名字'T',我的构造函数在哪里.
知道怎么解决吗?
所以我有一个接受不同构造函数的函数,如下所示:
export class SomeSuperClass {
...
}
export class A extends SomeSuperClass {
...
}
export class B extends SomeSuperClass {
...
}
const foo = function(Clazz: SomeSuperClass){
const v = new Clazz();
}
foo(A); // pass the class itself
foo(B); // pass the class itself
Run Code Online (Sandbox Code Playgroud)
问题是这SomeSuperClass意味着Clazz将是 的一个实例SomeSuperClass,而不是SomeSuperClass它本身。
我尝试了这样的愚蠢事情(这显然不起作用):
const foo = function(Clazz: SomeSuperClass.constructor){
const v = new Clazz();
}
Run Code Online (Sandbox Code Playgroud)
这样做的正确方法是什么?
我可以将角度分量类称为类型吗?我看到了Ionic any用于组件的用途。在Typescript中是否可以声明仅需要组件类的参数类型?
我看到了这个问题,但是组件在构造函数中没有任何共同点:将 类作为参数传递会导致“不可更新”错误