Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

137
Views
Why does Typescript throw an error if the code that throws an error in my catch block is surrounded by an if statement?

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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 to Promise<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.)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!