我有一个带有重载构造函数的类。我还为该类提供了一个Factory函数,用于返回该类的实例。此工厂函数也被重载,并且工厂函数的所有重载语法都与重载的构造函数语法匹配。
我现在正在寻找一种方法来应用'将工厂函数调用到构造函数调用的参数,无需在工厂函数和构造函数之间复制逻辑,以减少参数类型和工厂函数,然后在不同的构造函数语法之间切换并专门打电话给他们。
一些代码澄清了上述内容:
var sel = document.getElementById("colorSelect");
sel.onfocus = function() {
var nodes = this.options;
for (i = 0; i < nodes.length; i++) {
nodes[i].style.color = nodes[i].style.color;
}
};
我尝试了几件事,包括下面的休息/传播方法,但TypeScript并不喜欢这样:
class X {
constructor()
constructor(noOfRows: number, noOfCols: number)
constructor(noOfRows: number, colNames: string[])
constructor(????) {
//Logic here deduct based on the arguments send into the call which version of the constructor is called and properly initialize the X instance
}
function createX(): X
function createX(noOfRows: number, noOfCols: number): X
function createX(noOfRows: number, colNames: string[]): X
function createX(????): X {
//Here I rather not touch the arguments at all, but just forward them into the constructor call
return new X(????)
}
有关如何(正确)执行此操作的任何建议吗?
TIA,
保
答案 0 :(得分:0)
你可以这样做:
class X {
constructor();
constructor(noOfRows: number, noOfCols: number);
constructor(noOfRows: number, colNames: string[]);
constructor(...args: any[]) {
// ...
}
}
interface XConstructor {
new (...args: any[]): X;
}
function createX(): X;
function createX(noOfRows: number, noOfCols: number): X;
function createX(noOfRows: number, colNames: string[]): X;
function createX(...args: any[]): X {
return new (X as XConstructor)(...args);
}
虽然没有导出XConstructor
另一种选择:
class X {
constructor();
constructor(noOfRows: number, noOfCols: number);
constructor(noOfRows: number, colNames: string[]);
constructor(a?: any, b?: any) {
// ...
}
}
function createX(): X;
function createX(noOfRows: number, noOfCols: number): X;
function createX(noOfRows: number, colNames: string[]): X;
function createX(a?: any, b?: any): X {
return new X(a, b);
}