【问题标题】:Typescript: function with conditional return type calling another such function打字稿:具有条件返回类型的函数调用另一个此类函数
【发布时间】:2021-04-23 13:23:26
【问题描述】:

基于this question,我有以下具有条件返回类型的函数:

function foo(arg: false): string
function foo(arg: true): number
function foo(arg: boolean): string | number {
  return arg ? 1 : 'hello'
}

function bar(arg: false): string
function bar(arg: true): number
function bar(arg: boolean) {
  return foo(arg)
}

但是,此代码无法在 return foo(arg) 行上编译并出现此错误:

No overload matches this call.
  Overload 1 of 2, '(arg: false): string', gave the following error.
    Argument of type 'boolean' is not assignable to parameter of type 'false'.
  Overload 2 of 2, '(arg: true): number', gave the following error.
    Argument of type 'boolean' is not assignable to parameter of type 'true'. ts(2769)
The call would have succeeded against this implementation, but implementation signatures of overloads are not externally visible.

我发现我可以通过将bar 更改为:

function bar(arg: boolean) {
  return arg ? foo(arg) : foo(arg)
}

但这给我的函数体增加了一个多余的三元条件。有没有更多“正确”/优雅的方法来解决这个问题?

【问题讨论】:

  • 如果您打算使用foo(arg: boolean): string | number 之类的签名调用该函数,那么您需要将其声明为重载签名之一 - 它是实现签名不这样做。
  • @kaya3 我打算用bar(true) 调用bar,返回numberbar(false),返回string。这是一个人为的最小示例,因此看起来很荒谬,但在现实世界的应用程序中,我有一个更复杂的功能。
  • foo 是需要bar 函数想要调用它的签名的那个。

标签: typescript


【解决方案1】:

在这里,这应该可以工作:

  public foo(arg: false): string;
  public foo(arg: true): number
  public foo(arg: boolean): string | number
  public foo(arg: boolean): string | number {
    return arg ? 1 : 'hello';
  }

  public bar(arg: false): string;
  public bar(arg: true): number;
  public bar(arg: boolean): number | string
  public bar(arg: boolean): number | string {
    return this.foo(arg);
  }

【讨论】:

    猜你喜欢
    • 2021-09-17
    • 2022-07-07
    • 2020-05-27
    • 2015-08-10
    • 2022-01-12
    • 1970-01-01
    • 1970-01-01
    • 2023-01-30
    相关资源
    最近更新 更多