I don't understand why this gives an error
function foo(): () => string {
return () => 123;
}
But this does not
function foo(): () => void {
return () => 123;
}
And also this will not give an error as well
function foo(): (a: number) => string {
return () => '123';
}
I explicitly type that returned function should accept one argument, then return a function that does not accept any, but TS does not give me any error.
Assigning a function of type () => number to something of type () => string clearly is a type error. However, for void as a return type, TypeScript is more lenient. From the handbook on the Assignability of Functions:
The
voidreturn type for functions can produce some unusual, but expected behavior.Contextual typing with a return type of
voiddoes not force functions to not return something. Another way to say this is a contextual function type with avoidreturn type (type vf = () => void), when implemented, can return any other value, but it will be ignored.[…]
There is one other special case to be aware of, when a literal function definition has a
voidreturn type, that function must not return anything.
There's also an FAQ entry about it.
My investigations ended up with a fact that it is impossible to do this with TypesScript, unfortunately.
Here are the links that explain why this unintuitive decision was made
The solution that is closest to the desired functionality is to
function foo(): () => undefined { ... }
tsconfig.json"compilerOptions": {"noImplicitReturns": false}
function foo(): () => undefined {
return () => { return; }
}
Looks a bit ugly but now we can define a function that for sure will return nothing.