Has anybody done constructor overloading in TypeScript. On page 64 of the language specification (v 0.8), there are statements describing constructor overloads, but there wa
We can simulate constructor overload using guards
interface IUser {
name: string;
lastName: string;
}
interface IUserRaw {
UserName: string;
UserLastName: string;
}
function isUserRaw(user): user is IUserRaw {
return !!(user.UserName && user.UserLastName);
}
class User {
name: string;
lastName: string;
constructor(data: IUser | IUserRaw) {
if (isUserRaw(data)) {
this.name = data.UserName;
this.lastName = data.UserLastName;
} else {
this.name = data.name;
this.lastName = data.lastName;
}
}
}
const user = new User({ name: "Jhon", lastName: "Doe" })
const user2 = new User({ UserName: "Jhon", UserLastName: "Doe" })