打字稿中的静态方法中的泛型

时间:2017-12-28 13:39:01

标签: angular typescript

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

我想有这样的Module.register<AboutModule>([AboutService]),它告诉模块和提供者注册该模块,但我不知道如何使用typescript泛型 任何人都可以帮助我。

另外,param类型应该只接受类型而不是其他类型。假设我想要只接受类类型的参数。

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

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

您可以使用自定义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>;

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

并要求一组类作为参数。

类型不能在方法本身内部使用,这根本不能在打字稿中完成,因为你无法在运行时获得类型的类。

随意浏览我链接的github中的代码,我们有这个问题并使用此自定义类类型解决了它。

相关问题