【问题标题】:Generics in static methods in typescript打字稿中静态方法中的泛型
【发布时间】:2017-12-28 21:43:01
【问题描述】:
export class Module {
  static register<T>(provider: Array<Provider>): ModuleWithProviders {
     return {
        ngModule: T, // error type is being used as value
        providers: provider
     };
}

我想要类似Module.register&lt;AboutModule&gt;([AboutService]) 这样的东西,它告诉模块和提供者向该模块注册,但我不知道如何使用打字稿泛型来做到这一点 谁能帮我解决这个问题。

还有什么应该是只接受类型而不接受其他类型的参数类型。假设我想要一个只接受类类型的参数。

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

非常感谢任何帮助。

【问题讨论】:

  • 为什么不让它(klass: typeof T, provider: Array&lt;Provider&gt;)?然后你称它为.register(AboutModule, [AboutService]),T 是从第一个参数推断出来的。
  • @jonrsharpe 当我使用 klass: typeof T 它的抛出错误仅称为类型但用作值
  • 你还需要ngModule: klass,而不是T。
  • @jonrsharpe static register(klass: typeof T, provider: Array): ModuleWithProviders { return { ngModule: klass, providers: provider }; } 但我仍然收到错误。我在 kclass 收到此错误:typeof T line

标签: angular typescript


【解决方案1】:

您可以使用自定义的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 中的代码,我们有这个确切的问题并使用这个自定义类类型解决了它。

【讨论】:

    猜你喜欢
    • 2017-03-03
    • 2021-08-13
    • 1970-01-01
    • 1970-01-01
    • 2020-09-11
    • 2021-04-27
    • 2020-05-26
    • 2012-08-26
    • 2021-10-27
    相关资源
    最近更新 更多