【发布时间】:2020-05-18 05:19:33
【问题描述】:
如果我有以下代码:
abstract class Base {
}
class Extended extends Base {
}
abstract class BaseService {
protected static entity = Base
public getEntity() {
return (this.constructor as typeof BaseService).entity
}
}
class ExtendedService extends BaseService {
protected static entity = Extended
}
const entityClass = new ExtendedService().getEntity();
const entityClass 的类型是“typeof Base”,尽管它实际上是 Extended 类。有没有一种方法可以在 BaseService 中定义 getEntity,以便它的返回类型由用于创建服务实例的类中的静态实体确定(在本例中为 ExtendedService,但也适用于扩展 BaseService 的任何其他类?
【问题讨论】:
-
哎呀,你可以得到something like what you want,但它不是特别漂亮。
-
如果你没有使用
static属性,我会告诉你使用polymorphicthis。但是没有static polymorphicthis,也没有strong typing forconstructor,所以你不能直接这样做。如果你模拟constructor的强类型,将protected变成public,然后眯着眼睛,你可以得到你想要的行为。我应该写这个作为答案,还是你需要别的东西? -
感谢@jcalz 的解释!感谢您的帮助!我也在处理我有一个方法返回实体实例的情况(这里没有为实体使用抽象类),但我无法弄清楚这一点。我希望使用 InstanceType
,但我得到“类型'Base'不可分配给类型'InstanceType '” -
我想我需要看到一个minimal reproducible example 来提供建议;不确定是要将其编辑到当前问题中还是创建一个新问题。
-
当然可以。 something like this
标签: typescript