I'm trying to use destructed fields with inferred guards, however I'm not sure how to pass those guards to a separate function, for example:
function fn() {
if (Math.random() > 0.5) return { fail: true }
return { val: 5 }
}
function fn2() {
const { fail, val } = fn()
if (fail) return
// 'val' is possibly undefined
return val + 5 // vs: val! + 5
}
== EDIT
I was hoping to infer the union, but decided to manually create it.
type T = {
fail: true
val?: never
} | {
fail?: never
val: number
}
function fn(): T {
if (Math.random() > 0.5) return { fail: true }
return { val: 5 }
}
function fn2() {
const { fail, val } = fn()
if (fail) return
return val + 5
}