TypeScript doesn't want you to do this, see the FAQ. A function that returns a non-void
value can be used wherever a void
-returning function is needed. In TypeScript, a void
return type means "you should not try to use the return value of this function" and not "this function really doesn't return a value". So the most conventional answer to this question is that you should not need to enforce such a restriction; if anyFunction
returns a value, it will be ignored, which should be fine.
If you really want to bend the rules so that TypeScript will enforce the restriction, one thing you can do is this:
function higherOrderFunction<P extends any[]>(anyFunction: (...a: P) => undefined | void) {
return (...args: P) => { anyFunction(...args); };
}
By specifying undefined | void
you are saying you'll accept an undefined
return value (which should be okay, right?) or otherwise a function that doesn't return (using void
in a union seems to circumvent the compiler's "any value is fine" logic here):
higherOrderFunction(() => 1); // error, number is not undefined
higherOrderFunction(() => undefined); // okay
higherOrderFunction(() => console.log("this is void returning")); // okay
Or, if you want to make the compiler reject even undefined
-returning functions, you could use a generic signature that infers return type and then makes things not work unless the type it infers is void
:
function higherOrderFunction<P extends any[], R>(
anyFunction: (...a: P) => R & (void extends R ? void : never)
) {
return (...args: P) => { anyFunction(...args); };
}
The type (void extends R ? void : never)
evaluates to void
if R
is void
, and never
otherwise. So you get this behavior:
higherOrderFunction(() => 1); // error, number is not never
higherOrderFunction(() => undefined); // error, undefined is not never
higherOrderFunction(() => console.log("this is void returning")); // okay
Those methods "work" in that they enforce the restriction for the example use case, but there are likely to be edge cases. The most obvious edge case is that the following code has nothing to do with higherOrderFunction
and will not generate a warning:
const thisIsAllowed: () => void = () => 1; // okay
After all, non-void-returning functions are assignable to void-returning functions. And now the compiler sees thisIsAllowed
as a void
-returning function; it has forgotten all about the 1
.
And so, no matter how higherOrderFunction()
is defined so as to "require" a void
return, there will be no error here:
higherOrderFunction(thisIsAllowed); // no error
That might be a deal-breaker for you, depending on your use case.
I think the best thing to do here is probably to embrace TypeScript's viewpoint that a void
return type means "ignore any value returned" and not "no value is returned", and move on. Maybe the above rule-bending methods will still be of some use to you, but you shouldn't rely on them to prohibit functions that return values.
Okay, hope that helps; good luck!
Playground link