【发布时间】:2021-04-16 22:41:02
【问题描述】:
如何定义作为另一个类的子类的类型(包括父类上的静态方法)?
简化示例
假设我有两个抽象基类和两个具体子类(每个子类一个):
abstract class BaseEntity {
foo?: string;
static init<T extends BaseEntity>(this: new () => T, data: Partial<T>): T {
return Object.assign(new this(), data);
}
}
class FooBarEntity extends BaseEntity {
bar?: string;
}
abstract class BasePrinter<T extends BaseEntity> {
constructor(
private entityClass: typeof BaseEntity // <-- This would work if BaseEntity weren't abstract.
// What should I do instead of this?
) {}
initAndPrint(data: Partial<T>) {
const entity = this.entityClass.init(data);
console.log(entity);
}
}
class FooBarPrinter extends BasePrinter<FooBarEntity> {
// ...
}
目标
我希望能够做到这一点:
const myPrinter = new FooBarPrinter(FooBarEntity);
myPrinter.initAndPrint({ foo: 'FOO', bar: 'BAR' }); // FooBarEntity { foo: 'FOO', bar: 'BAR' }
我可以定义一个包含一个名为 initAndPrint 的函数的类型,但如果可以的话,我希望找到一种更通用/通用的方法。
【问题讨论】:
标签: typescript typescript-typings typescript-generics