简体   繁体   中英

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. Eg

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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM