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 thecatch
. 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
1 Answer
Reset to default 9Typescript 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>