Typescript:调用具有`this`参数的静态函数
我现在正在用打字机打字 基本上,我想从扩展特定抽象类的类调用静态函数 我得到以下错误Typescript:调用具有`this`参数的静态函数,typescript,Typescript,我现在正在用打字机打字 基本上,我想从扩展特定抽象类的类调用静态函数 我得到以下错误 类型为“typeof A”的“this”上下文不能分配给类型为“AStatic”的方法的“this” 代码如下: type AStatic={new():S}; 抽象A类{ 静态callStatic(this:AStatic){ console.log('hey') } } B类扩展了A类{ } 类D扩展了{ } C类{ A型:A型; 构造器(类型:A型){ this.aType=type; this.aTyp
类型为“typeof A”的“this”上下文不能分配给类型为“AStatic”的方法的“this”
代码如下:
type AStatic={new():S};
抽象A类{
静态callStatic(this:AStatic){
console.log('hey')
}
}
B类扩展了A类{
}
类D扩展了{
}
C类{
A型:A型;
构造器(类型:A型){
this.aType=type;
this.aType.callStatic();//此处有错误
}
}
常数c=新的c(B);
常数c_2=新的c(D);
我在typescript中构建它的唯一方法是通过传递any
而不是typeof A
。这只是一个遗憾,因为我没有得到IDE对a函数的支持
请注意,我无法控制类A和类型AStatic,因为它们来自外部库。您试图调用的是A的显式实例,这是不必要的
type AStatic<S extends A> = { new(): A };
abstract class A {
static callStatic<S extends AStatic<S>>(this: AStatic<S>) {
console.log('hey')
}
}
class B extends A {
}
class C {
aType: typeof A;
constructor(type: typeof A) {
this.aType = type;
B.callStatic()
}
}
const c = new C(B);
type AStatic={new():A};
抽象A类{
静态callStatic(this:AStatic){
console.log('hey')
}
}
B类扩展了A类{
}
C类{
A型:A型;
构造器(类型:A型){
this.aType=type;
B.callStatic()
}
}
常数c=新的c(B);
因为方法callStatic是静态的,所以您可以在B中调用此方法的实现。您就接近了!查看a
的伪定义:
abstract class A {
static callStatic<S extends AStatic<S>>(this: AStatic<S>) {
// ^^^^^^^^^^^^^^^^
// the `this` parameter must be type AStatic<A>
这排除了typeof A
作为This
参数的可能性,因为它是抽象的
。我们可以直接使用AStatic
:
class C {
aType: AStatic<A>;
constructor(type: AStatic<A>) {
this.aType = type;
this.aType.callStatic();
// ^^^^^^^^^^ - Property 'callStatic' does not exist on type 'AStatic<A>'
}
}
但是,正如蒙斯曼指出的,除非在派生类型上重写callStatic
,否则根本不需要传递typeof A
:
const c = new C(B);
c.callStatic(); // hey
B.callStatic(); // hey
D.callStatic(); // hey
换句话说,只要您有一个非抽象版本的a
,就可以对该类型调用callStatic
(或任何静态方法/属性),并且每次都会以相同的方式工作 好的,更具体地说,在我的例子中,我有许多类扩展了A,并且需要能够对其中任何一个调用静态函数,而不仅仅是B。我更新了我的问题以更好地表示我的情况。@ConnorLow你是指作为参数传递给静态函数的this
?如果是这样,正如我所说的,我无法控制函数定义,因为它位于外部库中。我只能控制B类、C类和DI类收回我的评论。我看到您使用的是A的类型
而不是A
。完全不同,塞纳里奥,我错过什么了吗?我在typescript游乐场尝试了您的解决方案,但它似乎对我不起作用,我得到以下错误this.aType.prototype.callStatic不是一个函数
:ISorry,修复并测试了我的答案。现在应该好了!哇!非常感谢。我不知道我们可以做工会会员!这对我很有效:)@Solal我做了一个更正。它们实际上被称为和的交叉点类型|
是一个联合体;我的错。尽管如此,效果仍然相同:)
class C {
aType: AStatic<A> & typeof A
constructor(type: AStatic<A> & typeof A) {
this.aType = type;
this.aType.callStatic() // works!
}
}
const c = new C(B);
c.callStatic(); // hey
B.callStatic(); // hey
D.callStatic(); // hey