Skip to content

Instantly share code, notes, and snippets.

@bennycode
Created May 15, 2022 20:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bennycode/fac4fe0c2e8f53a62f1349981b236b4c to your computer and use it in GitHub Desktop.
Save bennycode/fac4fe0c2e8f53a62f1349981b236b4c to your computer and use it in GitHub Desktop.
Function Overloading
function sum(a: number, b: number): number;
function sum(a: string, b: string): string;
function sum(a: number | string, b: number | string): number | string {
if (typeof a === "number" && typeof b === "number") {
return a + b;
} else {
return `${parseInt(`${a}`, 10) + parseInt(`${b}`, 10)}`;
}
}
const sumAsNumber = sum(1000, 337);
const sumAsString = sum("1000", "337");
console.log(sumAsNumber, typeof sumAsNumber);
console.log(sumAsString, typeof sumAsString);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment