我在使用Typescript进行依赖注入时遇到了一些问题。在每个类上,我都添加一个工厂静态方法,其中设置了所有依赖项。我这样做是为了测试目的,以便我仍然能够使用 TDD 方法。
现在,我在子类中重写父类的工厂方法时遇到了一些问题。 示例:
interface DepsA {
a: string
}
interface DepsB extends DepsA {
b: Child1
}
class Parent {
constructor(protected deps: DepsA | DepsB) {}
public static factory<T extends Parent>() {
return new this({a: 'This is a nice Dependency'}) as T
}
}
class Child1 extends Parent {}
class Child2 extends Parent {
public static factory() {
return new this({a: 'This is a nice Dependency', b: Child1.factory()})
}
}
const child1 = Child1.factory<Child1>()
const child2 = Child2.factory()
我收到的错误是:
[ts]
Class static side 'typeof Child2' incorrectly extends base class static side 'typeof Parent'.
Types of property 'factory' are incompatible.
Type '() => Child2' is not assignable to type '<T extends Parent>() => T'.
Type 'Child2' is not assignable to type 'T'.
我知道为什么我会收到错误,但此时已经不知道如何解决它,除了重命名 Child2 中的出厂静态方法。
更新:此问题的相关错误报告,自动解释了为什么我在工厂方法上使用通用方法是:#26298
首先,有一个名为 InstanceType 的预定义条件类型,它可以帮助您从静态成员推断类类型:
public static factory<T extends typeof Parent>(this: T) {
return new this({ a: 'This is a nice Dependency' }) as InstanceType<T>
}
其次,如果你在子类中重写一个方法,无论是否静态,它应该有一个兼容的签名,包括泛型的东西。
因此,您的代码块可能如下所示(请参阅Typescript Playground(:
interface DepsA {
a: string
}
interface DepsB extends DepsA {
b: Child1
}
class Parent {
constructor(public deps: DepsA | DepsB) {}
public static factory<T extends typeof Parent>(this: T) {
return new this({ a: 'This is a nice Dependency' }) as InstanceType<T>
}
}
class Child1 extends Parent {}
class Child2 extends Parent {
public static factory<T extends typeof Parent>(this: T) {
return new this({a: 'This is a nice Dependency', b: Child1.factory()}) as InstanceType<T>
}
}
const child1 = Child1.factory() // Type: Child1
const child2 = Child2.factory() // Type: Child2
从那里,在非静态成员中使用 as this["deps"]
返回正确的 deps
类型而不是联合。但是你必须修改一些你的代码。
希望它有帮助;-(