class BaseDoc {
static Collection;
static find(){
// which is expected to return an instance of SubDoc when run SubDoc.find()
return this.Collection.find();
}
}
class SubDoc extends BaseDoc {}
我希望是:运行SubDoc.find()时,应用程序知道返回值的类型是SubDoc的实例,而不是BaseDoc的实例。
我该如何实现?
答案 0 :(得分:1)
您可以创建通用版本的find
,该通用版本将把this
参数推断为所调用的类的类型,并使用InstanceType<T>
提取实际的实例类型从类中输入:
class BaseDoc {
static Collection: any;
static find<T extends typeof BaseDoc>(this: T): InstanceType<T> {
// which is expected to return an instance of SubDoc when run SubDoc.find()
return this.Collection.find();
}
}
class SubDoc extends BaseDoc {
}
SubDoc.find() // return SubDoc
或者您可以强制派生类定义适当类型的通用Collection
成员:
class Collection<T> {
find(): T {
return null as any // dummy imeplmentation
}
}
type GetCollectionItem<T extends Collection<any>> = T extends Collection<infer U> ? U: never;
class BaseDoc {
static Collection: Collection<BaseDoc>;
static find<T extends { new (... args: any[]) : any, Collection: Collection<any> }>(this: T): GetCollectionItem<T['Collection']> {
// which is expected to return an instance of SubDoc when run SubDoc.find()
return this.Collection.find();
}
}
class SubDoc extends BaseDoc {
static Collection: Collection<SubDoc>;
}
SubDoc.find() // return SubDoc