Skip to content

Instantly share code, notes, and snippets.

@dakshinasd
Created February 11, 2022 19:23
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 dakshinasd/e21c30646f72a8ae81f395fc4a91525a to your computer and use it in GitHub Desktop.
Save dakshinasd/e21c30646f72a8ae81f395fc4a91525a to your computer and use it in GitHub Desktop.
TypeScript Function Overload
// 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