简体   繁体   中英

Typescript: function with conditional return type calling another such function

Based on this question , I have the following functions with conditional return types:

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)
}

However, this code doesn't compile on the line return foo(arg) with this error:

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.

I found out I can make this work by changing bar to:

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

But that adds a redundant ternary condition to my function body. Is there any more "correct" / elegant way to fix this?

Here, this should work:

  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);
  }

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