Typescript: don't support multiple constructors?

Created on 14 Jun 2017  路  6Comments  路  Source: microsoft/TypeScript



TypeScript Version: 2.4.0 / nightly (2.5.0-dev.201xxxxx)

Code

// A *self-contained* demonstration of the problem follows...
class Person {
    private name: string;

    constructor() {

    }

    constructor(name: string) {
        this.name = name;
    }
}

Expected behavior:
compile pass

Actual behavior:
error: Multiple constructor implementations are not allowed.

Question

Most helpful comment

Because Javascript itself does not allow, and TS does not want to add more runtime behavior (see TS design goal).

All 6 comments

Did you mean constructor overloads?

class Person {
    private name: string;

    constructor();
    constructor(name: string);
    constructor(name?: string) {
        this.name = name;
    }
}

Or what you mean is something just like C++ does? See https://github.com/Microsoft/TypeScript/issues/12041#issuecomment-272782978.

I mean, Multiple constructor implementations, just like below:

class Person {
    private name: string;

    constructor() {}

    constructor(name: string) {
        this.name = name;
    }
}

as you see, there are two implementations
and I don't understand constructor(); means, how does it work?

I think multi-implementations should be duplicate of https://github.com/Microsoft/TypeScript/issues/12041.

EDIT: constructor(); is just a way to show that it can be a 0-param constructor.

EDIT: See TypeScript Docs: Function - Overloads for more about overloads.

thank you!

I don't know why the constructor can't be more.
It's ok in JAVA or C++

Because Javascript itself does not allow, and TS does not want to add more runtime behavior (see TS design goal).

Was this page helpful?
0 / 5 - 0 ratings

Related issues

dlaberge picture dlaberge  路  3Comments

Zlatkovsky picture Zlatkovsky  路  3Comments

seanzer picture seanzer  路  3Comments

siddjain picture siddjain  路  3Comments

manekinekko picture manekinekko  路  3Comments