I'm trying to throw an error if the error status code is anything but 401, however, as soon as I enclosed the line of code that throws the error, my typescript started giving me the following error:
Function lacks ending return statement and return type does not include 'undefined'.
My function looks like this:
export const addAccountGoal = async (title: string, color: string): Promise<number> => {
try {
const { body: goalId } = await request.post('/goals/account/addGoal').send({ title, color });
await setActiveGoal(goalId);
return goalId;
} catch (e) {
if (e.status !== 401) {
throw new Error('GENERIC_ERROR');
}
}
};
Once I remove the if statement in the catch block, I stop getting this error.
CodePudding user response:
To annotate your function a bit:
export const addAccountGoal = async (title: string, color: string): Promise<number> => {
try {
const { body: goalId } = await request.post('/goals/account/addGoal').send({ title, color });
await setActiveGoal(goalId);
return goalId;
} catch (e) {
if (e.status !== 401) {
throw new Error('GENERIC_ERROR');
} else {
// WHAT SHOULD I DO HERE
}
}
};
Your problem is that you haven't told TypeScript anything for "what should I do here", so execution continues to the end of the function, where you don't return anything. Hence the error message, "Function lacks ending return statement and return type does not include 'undefined'."
Depending on the specific logic you want:
- You could explicitly
return undefined;
and change the function's return type toPromise<number | undefined>
. - You could re-throw the error (
throw e;
). - You could return a default value (
return 0;
). - Something completely different
(The else {
that I added is just for explanatory purposes; you don't have to write your code that way unless you want to.)