Currently, I am in the process of converting frontend Java code to TypeScript and one challenge I am facing is dealing with method overloading.
I originally wanted to define the types like this:
const person = (info: {name:string, age:number} | {man:boolean}): void => {
if (typeof info.man === "boolean") {
console.log("man is defined", info.man);
} else {
console.log(info.name, info.age);
}
}
person({name:"Joe", age:25});
person({ man: false});
However, to satisfy TypeScript, it ended up looking like this:
const person = (info: {name:string, age:number, man?:undefined}
| {name?:string, age?:number, man:boolean}): void => {
if (typeof info.man === "boolean") {
console.log("man is defined", info.man);
} else {
console.log(info.name, info.age);
}
}
person({name:"Joe", age:25});
person({ man: false});
I am really hoping that there exists a cleaner and more readable way to define these types.