2

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?

1
  • 1
    Please add the error message to your question Commented Mar 20, 2016 at 15:42

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. I expected the reader to figure out it was wrapped in a class when I said so.
am I missing the magic syntax for using private and ... in a constructor or is it not possible? constructor(private ...steps: Step[])
Not sure, but I'd guess it is not supported. At least it does not feel right to me to accept multiple parameters as private field.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.