简体   繁体   English

如何在 typescript 中实现过载

[英]how to achieve overload in typescript

I konw there is a way in typescript like this:我知道 typescript 中有这样的方法:

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. TypeScript 是 JavaScript,所以你基本上必须做同样的事情。 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 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.您可以在代码中使用这些来告诉 TypeScript 您已经验证了运行时的类型。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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