Reputation: 343
How to write Function That Take different type of input ?
I want to write a function that take Victor as (array | object : {x , y}); But TypeScript Complain A lot!
I t
function dist(x1,y1,x2 = 0,y2 = 0) {
if (x1?.constructor == Array && y1?.constructor == Array) {
return dist(...x1, ...y1);
}
if (x1?.constructor == Object && y1?.constructor == Object) {
return dist(x1.x, x1.y, y1.x, y1.y);
}
let a = x2 - x1,
b = y2 - y1;
return Math.sqrt(a * a + b * b);
}
console.log(
dist(0,0,1,1),
dist([0,0],[1,1]),
dist({x:0,y:0},{x:1,y:1})
)
hink This is not right way to do this. Also TypeScript not Happy at All.
Upvotes: 1
Views: 149
Reputation: 101
maybe thats the thing you're looking for:
function divide(x: number, y: number): number;
function divide(str: string, y: number): string[];
function divide(x: any, y: number): any {
if (typeof x == 'number') {
return x / y;
} else if (typeof x == 'string') {
return [x.substring(0,y), x.substring(y)];
}
}
let n: number = divide(6, 2);
console.log(n);
let s: string[] = divide("football",4);
console.log(s);
More to read: overloading functions in JS
Upvotes: 1