方法重载不适用于Typecsript

我正在努力解决 Typescript 上的函数重载问题,也许有人能够更深入地解释它是如何工作的。

所以,任务很简单:我有一个类Point,上面x, y: number变量。

我需要用三个实现创建函数距离,实现是:

- no args: distance from this point to (0, 0);
- `distance(other: Point)` - distance from this point to a given instance of
    `Point`;
- `distance(x, y)` - distance from this point to a given point (x, y).

我的代码是:

  distance(): number;
  **distance**(other?: Point): number;
  distance(x?: number, y?: number) {
      return 42;
  }

linter一直用这个对我大喊大叫:

我怎样才能达到预期的结果来满足条件?

我知道如果我有原始类型怎么办,但是我在第二个实现中为这个特定的“点”类型而苦苦挣扎。

如果我写类似的东西other?: Point | {x?: number, y?: number}也行不通。

很高兴获得有关此问题的任何信息或有用的链接资源。

回答

这些用 Typescript 编写的方式基本上是:

signature1()
signature2()
implementationThatCombinesAllPreceding();
signature1()
signature2()
implementationThatCombinesAllPreceding();

所以如果我们想重写你的函数,它必须(可能)看起来像这样:

第 4 个“实现”签名不会出现在用户的自动完成系统中,因此您不必担心它“丑陋”。

但它是所有 3 个早期签名的组合。在函数体内部,您必须根据调用的形式的参数类型来确定。


以上是方法重载不适用于Typecsript的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>