|
|
|
|
|
by zarzavat
1713 days ago
|
|
void implies that the return type should is undefined behavior and should not be relied upon, so that something like this const x = foo();
is incorrect when foo() returns void. 99% of the time x will be undefined (the value) but there are cases where it would not be. For example arr.forEach(x => x.sort())
sort returns a value as well as having a side effect. But forEach expects a void callback. This code is perfectly fine in JavaScript because forEach does not read the return value of the callback. |
|
Type it as void if the value isn't really important to the caller, or you'll throw exceptions in an exceptional case.
Common wisdom is to always have user-defined functions return void, but sometimes I think it's okay to use void if you're replacing a built in JavaScript functionality so the outer code was relying on that semantic. For example, replacing a simple usage of findIndex (that returned undefined) with something more complex that does API calls.