Search code examples
javascripttypescriptpromiseasync-awaitreturn

Omitting return in async typed function


Let's see an example:

export async function foo(): Promise<string>{
  await bar()
  return;
}

It compiles without an error.

Then,

export async function foo(): Promise<string>{
  await bar()
}

results in error

A function whose declared type is neither 'void' nor 'any' must return a value

1) Why?

I guess it is something with https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#63-function-implementations

and complicated by using async, typescript and its typing?

UPDATE:

FYI, when function has return; has not return (or even has return undefined;), it is the same situation from the semantics perspective, right?


Solution

  • The point of explicitly providing a return type other than Void or Any is that you want to ensure type safety. And you implicitly tell the compiler that you actually want to return something. That's why the compiler expects you to do this and complains when you don't. It's defined in the TypeScript specification section 6.1:

    An explicitly typed function whose return type isn't the Void type, the Any type, or a union type containing the Void or Any type as a constituent must have at least one return statement somewhere in its body

    As for your question concerning return, you are right.

    return; and return undefined; have the same outcome, that's defined by the ECMAScript specification section 13.10:

    If Expression is omitted, the return value is undefined.

    Omitting the return statement also has the same effect, as defined in section 9.2.1. Step 11 basically says that undefined is returned if nothing else has been returned (Step 9) or no exception has been thrown (Step 10).

    So while your examples lead to the same result (returning undefined) in JavaScript, they are semantically different for the TypeScript compiler (the second ex. doesn't return anything).