Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript doesn't see return values from try/catch

I have a function that does some database operations. The implementation is wrapped in a try/catch block. E.g

async function update({id, ...changes}): Promise<IUserResult> {
 try {
  //code implementation here
  return updatedUser
 } catch(error) {
    console.error
 }
}

Typescript compiler always throws an error that I return undefined. I know this is so because I don't return any value explicitly from the function block itself but from the try/catch block. How do I go about this? I am just learning typescript and I was wondering how to get the return values to match the function return type, in this case, the IUserResult.

Thank you very much.

like image 949
thatguy Avatar asked Oct 15 '25 13:10

thatguy


1 Answers

Typescript wants a valid return type for all cases, but you don't have any return in case of exception.

You need to return something in your catch (or maybe finally) block or make return type like Promise<IUserResult|void>

like image 110
crystalbit Avatar answered Oct 17 '25 13:10

crystalbit