Consider a simple function like this:
export const add = (num?: number) => {
const adder = (n: number) => {
if (!n) {
return num;
}
num = (num && num + n) || n;
return adder;
};
return adder;
};
Example usage:
const result = add(1)(2)(3)() // => 6
When called, add will either return next function that takes another number, or a final sum if no number is passed.
This would work as expected in plain js, however for typescript this will cause an error:
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)
This is because TS cannot determine if the next iteration returns a function or a number.
Question:
How to type this function correctly, so that TS does not throw an Error?