简体   繁体   English

Typescript 通用 Class 构造函数参数与 static 方法

[英]Typescript Generic Class Constructor Argument with static methods

So the basic problem I have is this.所以我遇到的基本问题是这个。

I have a base class from which all other classes are derived.我有一个基础 class 派生所有其他类。 It has a static method.它有一个 static 方法。 Something like this:像这样的东西:

class BaseClass {
  static blah() : string {
    return 'base';
  }
}

class OtherClass extends BaseClass {
  static blah() : string {
    return 'other';
  }
}

class DoesntExtend extends SomeOtherClass {

}

Then I have a function which I want to pass in the Class Constructor and call the static method, but I'm having trouble with the method signature.然后我有一个 function ,我想将它传入 Class 构造函数并调用 static 方法,但我遇到了方法签名的问题。

I want to use it something like this:我想像这样使用它:

console.log(funcCaller(BaseClass)) -> outputs 'base'
console.log(funcCaller(OtherClass)) -> outputs 'other'
console.log(funcCaller(DoesntExtend)) -> won't compile, since DoesntExtend won't have the static method

So I thought to do something like:所以我想做类似的事情:

type Constructor<T extends BaseClass > = new(...args: any[]) => T;

function funcCaller<T extends BaseClass>(c : Constructor<T>) : string {
  return c.blah();
}

but tsc complains that但 tsc 抱怨说

Property 'blah' does not exist on type 'Constructor'

any ideas?有任何想法吗?

The funcCaller function needs to accept typeof the class to access the static properties. funcCaller function 需要接受typeof类型才能访问 static 属性。 This is because static properties exist on the type while the signature you have used accepts an instance of that type.这是因为类型上存在 static 属性,而您使用的签名接受该类型的实例。 As the docs says , "To refer to the type that the value f has, we use typeof ". 正如文档所说,“要引用值 f 具有的类型,我们使用typeof ”。

TS Playground TS游乐场

class BaseClass {
  static blah() : string {
    return 'base';
  }
}

class OtherClass extends BaseClass {
  static blah() : string {
    return 'other';
  }
}

class DoesntOverride extends BaseClass{

}

class SomeOtherClass {
}

class DoesntExtend extends SomeOtherClass {

}

function funcCaller(c : typeof BaseClass) : string {
    return c.blah();
}

// base
console.log(funcCaller(BaseClass));

// other
console.log(funcCaller(OtherClass));

// base
console.log(funcCaller(DoesntOverride));

// Shows error
console.log(funcCaller(DoesntExtend));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM