您可以使用
the polymorphic
this
type
表示的“当前”子类的类型
AbstractClass
。然后我们可以这么说
prop
的类型是的返回类型
initialize
的方法
这
:
abstract class AbstractClass {
prop!: ReturnType<this["initialize"]>
abstract initialize(): Base
}
请注意
ReturnType<this["initialize"]>
正在使用
the
ReturnType
utility type
从函数类型中提取返回类型,以及
indexed access type
查找的类型
初始化
中的属性
这
.
让我们测试一下:
class UserClass1 extends AbstractClass {
initialize() {
return new Base()
}
someMethod() {
this.prop.method_1() // Valid, no TS error
this.prop.method_2() // Error, it doesn't exist in Base
}
}
class UserClass2 extends AbstractClass {
initialize() {
return new Child()
}
someMethod() {
this.prop.method_1() // Valid, no TS error
this.prop.method_2() // Valid, no TS error
}
}
看起来不错。在每种情况下,
道具
给定了类型
ReturnType<这个[“初始化”]>
,用于
UserClass1
已知只能分配给
Base
,而对于
UserClass2
已知可分配给
Child
.
Playground link to code