#Conditionally make a type not undefined

9 messages · Page 1 of 1 (latest)

jovial lake
#

How can I make sure my value is not undefined after checking the error, since they can't both be undefined.

function run<V>(fn: () => V): [V | undefined, Error | undefined] {
    let value
    let error
    try {
      value = fn()
    } catch (e) {
      error = e as Error
    }
    return [value, error]
  }
  
  const [value, error] = run(() => 1)
  if (error) return

  value: number | undefined // expected "number"
cyan hollow
#

You want a DU.

#

!hb disc

tawdry dragonBOT
cyan hollow
#

So [V, undefined] | [undefined, Error] would work.

jovial lake
#

That's what I tried, turns out i just had to cast the result to it as well thanks

cyan hollow
#

You don't have to.

#

You just need to change your code into:

function run<V>(fn: () => V): [V, undefined] | [undefined, Error] {
    try {
        return [fn(), undefined]
    } catch (e) {
        return [undefined, e as Error]
    }
}
#

(As a side note e as Error is unsafe, since JS allows you to throw anything and not limited to only Errors. But if you think that's a safe assumption to make then sure)