Peter
Peter

Reputation: 289

Constructor overload with spread operator Typescript

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

Answers (1)

ahz
ahz

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

Related Questions