Reputation: 15502
Why doesn't this result in a compiler error?
function foo(): () => void {
return () => Promise.resolve();
}
This particular case is important, because when a function returns a promise then the caller should know that the function isn't "done" until the promise resolves or rejects.
Promises are related to why this is a problem in the codebase I'm looking at, but it seems the combination of void
and function types get special treatment in general that I don't understand. Why would the first line in the following error, but not the second line?
const y: void = 3; // error
const x: () => void = () => 3; // OK
Am I misunderstanding the phenomenon? Is this a TypeScript bug?
Upvotes: 4
Views: 212
Reputation: 23174
As a simple rationale : if you use () => void
as a callback type, then it means you just won't expect a return value.
You just want to execute a function that takes no argument.
So, since you can also usually invoke functions that returns something and then just ignore the returned value, it follows that any function that returns something could be used in place of function marked as returning void
.
It might be surprising on the point of view of other languages, where the returned type matters for compilation. However, take into account that TypeScript takes roots in JavaScript, and there a function returning "nothing" ( function f() { return; }
) actually returns undefined
anyway. So all JS functions return something somehow, in this point of view.
Here is a similar explanation directly from the TypeScript FAQ:
Another way to think of this is that a void-returning callback type says "I'm not going to look at your return value, if one exists".
So, void
means "no restriction on the returned type" here.
If you want instead to forbid any returned type, then use () => undefined
, that is the minimal type that will be returned anyway, even by a void
function.
Upvotes: 4