Created
February 11, 2022 19:23
-
-
Save dakshinasd/e21c30646f72a8ae81f395fc4a91525a to your computer and use it in GitHub Desktop.
TypeScript Function Overload
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
// as per https://www.youtube.com/watch?v=XnyZXNnWAOA | |
interface Coordinate { | |
x: number; | |
y: number; | |
} | |
function parseCordinates(obj: Coordinate): Coordinate; | |
function parseCordinates(str: string): Coordinate; | |
function parseCordinates(num1: number, num2: number): Coordinate; | |
function parseCordinates(arg1: unknown, arg2?: unknown): Coordinate { | |
let coord: Coordinate = { | |
x: 0, | |
y: 0 | |
} | |
if (typeof arg1 === 'object') { | |
coord = { | |
...(arg1 as Coordinate) | |
} | |
} else if(typeof arg1 === 'string') { | |
(arg1 as string).split(',').map(fr => { | |
const [key, value] = fr.split(':'); | |
coord[key] = parseInt(value); | |
}) | |
} | |
else { | |
coord = { | |
x: (arg1 as number), | |
y: (arg2 as number) | |
} | |
} | |
return coord; | |
} | |
console.log(parseCordinates({x: 10, y: 20})); | |
console.log(parseCordinates(10, 78)) | |
console.log(parseCordinates('x:56,y:40')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment