简体   繁体   中英

how to achieve overload in typescript

I konw there is a way in typescript like this:

function foo(arg: number): string;
function foo(arg: string): number;
function foo(): any {
  if (typeof arguments[0] === "string") {
    return +arguments[0];
  } else {
    return arguments[0].toString();
  }
}

foo(1)       // '1'
foo("hello") // NaN 
foo("2")     // 2

But when I have same number of parameters and each parameter is custom type, like this


interface Dog {
  run: number;
}

interface Bird {
  fly: number;
}

function foo(arg: Dog): number;
function foo(arg: Bird): number;
function foo(): any {
}


How can I tell the difference between these parameters

TypeScript is JavaScript, so you basically have to do the same thing. In order to make your compiler happy, you can implement type guards.

https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards

function isDog(pet: Dog | Bird): pet is Dog {
  return 'run' in pet
}

You can use these in your code to tell TypeScript that you've validated the type for runtime.

function foo(arg?: Dog | Bird): void | number {
  if(arg) {
    if(isDog(arg)) {
      return arg.run;
    } else {
      return arg.fly;
    }
  }
}

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