我想在基类构造函数中使用变量参数。派生类中也是如此。构造函数可以接收未知数量的参数,我想将它们传递给基类构造函数,以进行一些处理。我没有找到任何合适的解决方案,而且似乎可以使用spread operator解决,显然TypeScript中没有。它将在1.5版中开发(对吗?):
class TSBase{
constructor(...args: any[]){
//do stuff with args
}
}
class TSSomeController extends TSBase{
constructor(...args: any[]){
//let base do some stuff
//super(...args); //this doesn't work, but it would be cool... :)
}
}
Run Code Online (Sandbox Code Playgroud)
在TypeScript中做到这一点的最佳方法是什么?我可以使用类似的东西super.prototype.apply
吗?
如您所知,扩展运算符尚不可用。
编辑-旁注:实际上,它现在可以在TypeScript 1.5中使用。做就是了super(...args);
至于在TypeScript 1.5之前执行此操作的最佳方法……这确实取决于,但这是一个解决方案,它不涉及更改任何派生类并保持您要执行的操作:
class TSBase {
constructor(...args: any[]) {
if (this.constructor != TSBase && args.length === 1 && args[0] instanceof Array) {
args = args[0];
}
// work with args here... for example:
args.forEach((val) => console.log(val));
}
}
class TSSomeController extends TSBase{
constructor(...args: any[]){
super(args);
}
}
new TSBase(3, 4); // 3, 4
new TSBase([3, 4]); // Array[2]
new TSSomeController(3, 4); // 3, 4
new TSSomeController([3, 4]); // Array[2]
new TSSomeController([3, 4], 5); // Array[2], 5
Run Code Online (Sandbox Code Playgroud)
基本上,您可以在基本构造函数中添加一个检查,以使args
数组仅在从派生类传入时,有一个参数且该参数是数组时才等于第一个元素。