最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Typescript GuardPredicate for object field - Stack Overflow

programmeradmin2浏览0评论

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
}
发布评论

评论列表(0)

  1. 暂无评论