Consider a basic function like this:
export const sum = (num?: number) => {
const adder = (n: number) => {
if (!n) {
return num;
}
num = (num && num + n) || n;
return adder;
};
return adder;
};
Example usage:
const total = sum(1)(2)(3)() // => 6
When called, sum
will either return the next function that takes another number, or the final sum if no number is passed.
While this works in plain JavaScript, TypeScript raises an error for this scenario:
This expression is not callable. Not all constituents of type 'number | ((n?: number | undefined) => (x?: number | undefined) => number | ...)' are callable. Type 'number' has no call signatures.ts(2349)
The error arises because TypeScript cannot determine whether the next iteration returns a function or a number.
Question:
How can this function be correctly typed so that TypeScript does not generate an error?