我正在尝试在Typescript中创建一个工厂类。应该设置工厂以创建特定的对象类,包括在工厂初始化时设置的默认参数。
这是到目前为止我要提出的:
type Constructor<T> = new(...args: any) => T;
class Factory<T> {
private params: ConstructorParameters<Constructor<T>>;
private ctor: Constructor<T>;
init<TCtor extends Constructor<T>>(tConstructor: TCtor,
...params: ConstructorParameters<TCtor>)
{
this.ctor = tConstructor;
this.params = params;
}
create(): T {
return new this.ctor(...this.params);
}
}
class ClassWithParams { constructor(a: number) { } }
const factory = new Factory<ClassWithParams>();
//factory.init(ClassWithParams);
// Compilation error - missing param a
factory.init(ClassWithParams, 1);
console.log(factory.create());
// instance of ClassWithParams
上面的代码运行良好(Typescript playground)。但是,它需要在构造后直接init()
致电工厂。我无法将init()
代码移到构造函数中,因为init()
依赖于通用参数TCtor
来正确地对参数列表进行类型检查。
我可以改为使TCtor
为该类的通用参数,但这意味着每次通用引用Factory时,都无缘无故需要提供一个附加的类型参数。
是否有删除该init()
通话的想法?
答案 0 :(得分:1)
以下代码有什么问题
type Constructor<T> = new (...args: any[]) => T;
class Factory<T, C extends Constructor<T> = Constructor<T>> {
params: ConstructorParameters<C>;
ctor: Constructor<T>;
constructor(tConstructor: Constructor<T>,
...params: ConstructorParameters<C>) {
this.ctor = tConstructor;
this.params = params;
}
create(): T {
return new (this.ctor)(...this.params)
}
}
class ClassWithParams { constructor(a: number) { this.a = a; } a: number }
const factory1 = new Factory(ClassWithParams);
const factory2 = new Factory(ClassWithParams, '1');
const factory3 = new Factory(ClassWithParams, 0);
const value = new Factory(ClassWithParams, 0).create().a;
如本playground所示,它是方便且正确的。