最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Typescript doesn't see return values from trycatch - Stack Overflow

programmeradmin1浏览0评论

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

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

Share Improve this question asked Dec 24, 2020 at 12:28 thatguythatguy 4201 gold badge9 silver badges27 bronze badges 1
  • 3 You return a value from the try but not the catch. If you’re not going to return something you’d need to update the function’s signature. – Dave Newton Commented Dec 24, 2020 at 12:33
Add a ment  | 

1 Answer 1

Reset to default 9

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>

发布评论

评论列表(0)

  1. 暂无评论