David Thielen
David Thielen

Reputation: 32976

What is the advantage of multiple constructors in typescript?

Let's say I have something like:

class MyClass {
    constructor(s: number);
    constructor(s: string);
    constructor(s: any) {

    }
}

What do those first 2 declarations buy me since the third one now allows anything to be passed in. Can the third (actual) one be made private? It looks like private is ignored on a constructor.

Upvotes: 0

Views: 470

Answers (1)

Ryan Cavanaugh
Ryan Cavanaugh

Reputation: 221232

The implementation signature, as it's called, is already not visible. You don't have to do anything to make it 'private'. Whenever a function or constructor is overloaded, only the overloads are seen by callers.

var x = new MyClass({n: 3}); // This is an error.

Upvotes: 1

Related Questions