简体   繁体   English

打字稿中静态方法的泛型

[英]Generics in static methods in typescript

export class Module {
  static register<T>(provider: Array<Provider>): ModuleWithProviders {
     return {
        ngModule: T, // error type is being used as value
        providers: provider
     };
}

I would like to have something like this Module.register<AboutModule>([AboutService]) which tells the module and providers to be registered with that module but I am not sure how to do this using typescript generics Could any one help me with this. 我想要类似Module.register<AboutModule>([AboutService]) ,它告诉模块和提供者要在该模块中注册,但是我不确定如何使用Typescript泛型来做到这一点。 。

Also what should be the param type to accept only types instead of other types. 同样,应仅接受类型而不接受其他类型的参数类型是什么。 Say I would like to have parameter that accepts only class types. 说我想拥有仅接受类类型的参数。

stats(list: ClassType){} // something like this
stats(list: any){} // currently im using this, how should I restrict param only to types.

Any help is greatly appreciated. 任何帮助是极大的赞赏。

You can use a custom Class type: 您可以使用自定义的Class类型:

export type Abstract<T = any> = Function & { prototype: T };

export type Instantiable<T = any> = new (...args: any[]) => T;

export type Class<T = any> = Abstract<T> | Instantiable<T>;

Source: https://github.com/kaiu-lab/serializer/blob/master/src/class.ts 来源: https : //github.com/kaiu-lab/serializer/blob/master/src/class.ts

And ask for an array of classes as parameters. 并要求一个类数组作为参数。

Types can't be used inside the method itself, this can't be done in typescript at all, because you can't get the class of a type at runtime. 类型不能在方法本身内部使用,这根本不能在typescript中完成,因为您不能在运行时获取类型的类。

Feel free to explore the code in the github I linked, we has this exact issue and solved it using this custom class type. 随意浏览我链接的github中的代码,我们有这个确切的问题,并使用此自定义类类型解决了。

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

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