Skip to content

don't support multiple constructors? #16518

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
GerryLon opened this issue Jun 14, 2017 · 6 comments
Closed

don't support multiple constructors? #16518

GerryLon opened this issue Jun 14, 2017 · 6 comments
Labels
Question An issue which isn't directly actionable in code

Comments

@GerryLon
Copy link

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.

@ikatyang
Copy link
Contributor

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 #12041 (comment).

@RyanCavanaugh RyanCavanaugh added the Question An issue which isn't directly actionable in code label Jun 14, 2017
@GerryLon
Copy link
Author

GerryLon commented Jun 22, 2017

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?

@ikatyang
Copy link
Contributor

ikatyang commented Jun 22, 2017

I think multi-implementations should be duplicate of #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.

@GerryLon
Copy link
Author

thank you!

@melodyJie
Copy link

melodyJie commented Aug 4, 2017

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

@ikatyang
Copy link
Contributor

ikatyang commented Aug 4, 2017

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

@microsoft microsoft locked and limited conversation to collaborators Jun 14, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Question An issue which isn't directly actionable in code
Projects
None yet
Development

No branches or pull requests

4 participants