【发布时间】:2019-03-27 08:12:55
【问题描述】:
为什么在 TypeScript 中不允许有单独的 constructor 定义?
拥有例如两个constructors,我需要这样写我的代码。
constructor(id: number)
constructor(id: number, name?: string, surname?: string, email?: string) {
this.id = id;
this.name = name;
this.surname = surname;
this.email = email;
}
因此,我需要将? 放在第一个构造函数中不需要的参数之后。
为什么我不能这样写?
constructor(id: number) {
this.id = id;
}
constructor(id: number, name: string, surname: string, email: string) {
this.id = id;
this.name = name;
this.surname = surname;
this.email = email;
}
因此对于两个构造函数来说,所有参数都是强制性的。
此外,如果我需要一个空的构造函数,事情会变得更奇怪,因为我需要用? 标记每个参数。
constructor()
constructor(id?: number, name?: string, surname?: string, email?: string) {
this.id = id;
this.name = name;
this.surname = surname;
this.email = email;
}
为什么 TypeScript 与 C# 或 Python 等常用语言在这里有所不同?
我希望它能像这样工作。
constructor() {
}
constructor(id: number, name: string, surname: string, email: string) {
this.id = id;
this.name = name;
this.surname = surname;
this.email = email;
}
所以你可以不传参数或者必须传所有参数。
【问题讨论】:
-
其实我根本不需要
constructor(),如果所有参数都标有?。 -
只是让您知道签名
()+(id?)不会暴露id签名。你需要()+(id)+(id?)。详情见我的回答 -
也不是每个公共重载都需要是可选的。所以你的公共界面可以是安全的。再次,请参阅我的答案。