0
我有一个具有重载构造函数的类。我也有一个返回该类实例的类的Factory函数。此工厂函数也被重载,并且工厂函数的所有重载语法都与重载的构造函数语法匹配。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(????)
}
我已经试过几件事情,包括像下面休息/传播途径,但打字稿不喜欢的是:
function createX(...args: any[]): X {
return new X(...args)
}
任何建议如何(正确)做到这一点?
TIA,
保罗
嗨卢塞罗,我认为你错了。 Javascript支持自ES6以来,使用扩展语法,请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator#Apply_for_new 这也已经暗示了你的线程链接到,但答案没有得到任何upvotes – Paul