Created
May 15, 2022 20:26
-
-
Save bennycode/fac4fe0c2e8f53a62f1349981b236b4c to your computer and use it in GitHub Desktop.
Function Overloading
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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