Reputation: 289
I am trying to overload my constructor for TypeScript Class
constructor(a: T[])
constructor(...a: T[]) {
a.forEach(e => {
//do something with e
});
}
Why does the compiler complain about the above? And any ideas how to fix it?
Upvotes: 2
Views: 2718
Reputation: 950
Provided code snippet is not a class. Assuming it is actually wrapped in class. This should work correctly (also in runtime):
class A<T> {
constructor(a: T[]); // first overload
constructor(...a: T[]); // second overload
constructor(a) { // implementation (should implement all overloads)
a = arguments.length === 1 ? a : Array.prototype.slice.call(arguments);
a.forEach(e => {
//do something with e
console.log(e);
});
}
}
var strings = new A<string>(['a']);
var numbers = new A<number>(1, 2, 4);
Read more in Handbook.
Upvotes: 7