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