简体   繁体   中英

how to use same function for different type of input?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM