TS7023
Recursive return type cannot be inferred
'factorial' implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions.The compiler’s own words. Not translated — this is the string you pasted into a search box.
A recursive function asks inference to know its return type before that same return type has been established.
Reproduction
function factorial(n: number) {
return n <= 1 ? 1 : n * factorial(n - 1)
}The build asserts this emits exactly this code.
Why the compiler says this
Inference follows the return expression, which calls the function whose return is currently being inferred. The cycle has no independent annotation to anchor it, so strict mode refuses to settle on `any`.
Fixes
- 01
function factorial(n: number): number { return n <= 1 ? 1 : n * factorial(n - 1) }
Annotate the recursive boundary explicitly; the body is then checked against it.
- 02
function factorial(n: number) { let result = 1 for (let value = 2; value <= n; value += 1) { result *= value } return result }An iterative form removes the inference cycle when recursion is not essential.
Takeaway
Recursive functions are a good place for explicit return types: the annotation both breaks the cycle and documents the invariant.
