函数返回实现接口的类的函数:缺少属性

时间:2020-10-13 09:07:53

标签: typescript nestjs

打字稿3.9 我想创建一个工厂函数,该函数返回一个实现特定接口的类:

export interface A<T>{
  list(): Promise<T>
}

export function Factory<T>(): A<T> {
  class AHost implements A<T>{
    async list() {
      return {} as any
    }
  }
  return AHost
}

但出现以下错误:

Property 'list' is missing in type 'typeof AHost' but required in type 'A<T>'.

尽管在list上定义了AHost。这极大地启发了NestJS author's talk。我无法一对一使用它,因为当我使用Type时会遇到TS2315: Type 'Type' is not generic.错误。

更大的景象是:我想使用EntityClassOrSchema(Typeorm)作为工厂函数的输入参数来创建抽象服务,以便我可以轻松地为各种实体生成服务。

1 个答案:

答案 0 :(得分:1)

您的工厂接口需要A实例,但不希望A类

您应该将工厂类型更改为类似

export interface A<T>{
  list(): Promise<T>
}
// add type of class there
export type B<T> = new () => A<T>

export function Factory<T>(): B<T> {
  class AHost implements A<T>{
    async list() {
      return {} as any
    }
  }
  return AHost
}
相关问题