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.
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).
Most helpful comment
Because Javascript itself does not allow, and TS does not want to add more runtime behavior (see TS design goal).