admin管理员组文章数量:1321815
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
}
本文标签: Typescript GuardPredicate for object fieldStack Overflow
版权声明:本文标题:Typescript GuardPredicate for object field - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742105476a2420999.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论