Search code examples
typescript

How can I deal with conditional exceptions in typescript?


I have this typescript code:

const loadSomething = () => {
  try {
    return {
      foo: 'bar'
    }
  } catch (e) {
    console.error(e)
    throw e
  }
}

const main = () => {
  const result = loadSomething()
  console.log(result.foo)
}

This code is totally fine and does not produce any typescript issues. But now I want to outsource the code which I use for handling the exception. So I change it like this:

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)
}

I need to conditionally throw that exception, but in that case typescript gives me the error that result is possibly undefined. But this can never occur, since I rethrow the exception in the catch block. Is there a way I can tell typescript that logError throws an exception if rethrow is true, so that the typescript issues are gone?


Solution

  • Thanks @Bergi for your answer. So I changed my code to this and have no typescript issues anymore:

    function logError(e: any, rethrow: false): void
    function logError(e: any, rethrow: true): never
    function logError(e: any, rethrow: boolean) {
      console.error(e)
      if (rethrow) {
        throw e
      }
    }
    
    const loadSomething = () => {
      try {
        return {
          foo: 'bar'
        }
      } catch (e) {
        logError(e, true)
      }
    }
    
    const main = () => {
      const result = loadSomething()
      console.log(result.foo)
    }