打字稿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)作为工厂函数的输入参数来创建抽象服务,以便我可以轻松地为各种实体生成服务。
答案 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
}