Here's a snippet of my TypeScript code:
const loadSomething = () => {
try {
return {
foo: 'bar'
}
} catch (e) {
console.error(e)
throw e
}
}
const main = () => {
const result = loadSomething()
console.log(result.foo)
}
The original code works perfectly without any TypeScript issues. However, I now want to externalize the exception handling part of my code. So, I made some changes:
const logError = (e: any, rethrow: boolean) => {
console.error(e)
if (rethrow) {
throw e
}
}
const loadSomething = () => {
try {
return {
foo: 'bar'
}
} catch (e) {
logError(e, true)
}
return undefined
}
const main = () => {
const result = loadSomething()
console.log(result.foo)
}
Now, I need to conditionally throw an exception, which results in TypeScript showing an error that result
could be undefined. But since I rethrow the exception in the catch block, this situation should not actually occur. Is there a way to inform TypeScript that logError
will throw an exception if rethrow
is true, so that these TypeScript issues can be resolved?