Typescript 函数重载 - 没有重载匹配此调用

时间:2021-06-14 14:46:39

标签: typescript

我正在编写一个函数,该函数调用另一个将枚举作为接受参数的函数。根据传递的值,函数的返回类型不同。

被调用的函数 (b) 和函数调用 (a) 都需要它们的参数符合枚举。我想知道为什么下面的代码会出现 Tyepscript 错误?

export function a (mode: 'a' | 'b') {
   return b(mode)
}
export function b (mode: 'a'): string
export function b (mode: 'b'): number
export function b (mode: 'a' | 'b'): string | number {
   return (mode=='a') ? 'string' : 1;
}

错误:

  No overload matches this call.
  Overload 1 of 2, '(mode: "a"): string', gave the following error.
    Argument of type '"a" | "b"' is not assignable to parameter of type '"a"'.
      Type '"b"' is not assignable to type '"a"'.
  Overload 2 of 2, '(mode: "b"): number', gave the following error.
    Argument of type '"a" | "b"' is not assignable to parameter of type '"b"'.
      Type '"a"' is not assignable to type '"b"'.ts(2769)
Cart.tsx(118, 18): The call would have succeeded against this implementation, but implementation signatures of overloads are not externally visible.

最接近的问题是 here,但我不想有一个模棱两可的签名 - 模式 'a' 应该总是返回字符串,而 'b' 总是数字。

2 个答案:

答案 0 :(得分:1)

这个问题是从 timetime 出现的。甚至在 same form 中作为您的问题。我相信这是现在跟踪进度的 main place。但目前还没有内置解决方案。

至于现在,您可以在 issues 之一中添加统一的重载或实现类似 jcalz 提出的内容。

答案 1 :(得分:0)

组合函数签名 (int a[1000] = {0}; ) 对调用者根本不可见。就 Typescript 编译器而言,只有 b (mode: 'a' | 'b'): string | numberb (mode: 'a'): string 存在。这也是错误信息最后一行的意思。

一个可能有助于解释为什么这是不可能的示例是事件侦听器:b (mode: 'b'): numberaddEventListener('click')addEventListener('keyDown') 不同。因此,这两个签名是完全独立的,您要么需要一个带有两个单独调用的 if 语句,要么需要一个带有联合类型的附加签名来修复错误。