Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

138
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda