简体   繁体   中英

Multiple / compound return types

Does this

function foo(): () => void | string

mean, that

a) the function foo may return a string, or another function which doesn't return anything; or

b) the function foo returns another function, which in turn may or may not return a string?

Also, how do you correctly and clearly denote the other option (whichever one is incorrect)?

function foo(): () => void | string function foo(): () => void | string : foo is a function that has no input params and it will return another function that the result of that will be void or string

function foo(): void | string function foo(): void | string : foo is a function that has no input params and it will return void or string

function foo(): (() => void) | string function foo(): (() => void) | string : foo is a function that has no input params and it will return string or another function that returns void

() => void | string () => void | string is the type of a function that may or may not return a string, which doesn't seem very useful since a function returning a string is already assignable to () => void .

If you wanted "either a function, or a string", you should use brackets: (() => void) | string (() => void) | string , the same way you would use brackets in any other case where you want to use operators not in order of precedence.

It means (b)

/**
 * The function foo returns another function,
 * which in turn may or may not return a string.
 */
function foo(): () => void | string;

// example implementation
function foo(): () => void | string {
  return () => {
    if (Math.random() % 2 === 0) {
      return "bar";
    }
  };
}

Here is how you would define (a)

/**
 * The function foo may return a string,
 * or another function which doesn't return anything.
 */
function foo2(): (() => void) | string;

// example implementation
function foo2(): (() => void) | string {
  if (Math.random() % 2 === 0) {
    return "bar";
  }

  return () => {};
}

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