In this scenario, there is a straightforward function called make
which utilizes the handle
function to retry a specified number of times if it encounters an error. Once all retries have been exhausted, the make
function should throw the error.
const handle = async (): Promise<string> => 'hi';
const make = async (): Promise<string> => {
const MAX_RETRIES = 2;
for (let idx = 0; idx <= MAX_RETRIES; idx++) {
try {
return await handle();
} catch (err) {
if (idx < MAX_RETRIES) {
continue;
} else {
throw err;
}
}
}
};
When utilizing TypeScript, an issue arises as the return type does not include undefined
:
Function lacks ending return statement and return type does not include 'undefined'.
You can view this code in the TS Playground.
The main question is how to manage the return type for this function.
It's important to note that:
- No alterations are to be made to existing tsconfigs (currently set to
strict
) - Avoid changing the return type to
Promise<string | undefined>
As per understanding, the make
function will either return a string
during the try
block or ultimately throw an error after exhausting retries. Thus, where does the request for undefined
from TypeScript originate? Is anything being overlooked?