Нужно явно рассказать TS-у что если аргумент falsy, то результатом будет число, а в остальных случаях новая функция.
Например так (
песочница):
type StepFn = (val?: number) => number | StepFn;
function add(val: number): typeof add;
function add(val: 0): number;
function add(): number;
function add(val?: number): number | StepFn {
if (val) {
return function sum(next?: number): number | StepFn {
if (!next) {
return val;
}
return add(val + next);
};
} else {
return 0;
}
}
console.log(add());
console.log(add(1)(2)());
console.log(add(2)(4)(6)());
console.log(add(4)(6)(8)(10)());