首页 > 解决方案 > 打字稿守卫在联合类型上失败

问题描述

customer.id我不明白为什么 TypeScript在这个例子中抱怨一个可能的未定义对象( ):

type Customer = {
  id: string
  company: string
}

type Props =
  | {
      mode: 'new'
      customer: undefined
    }
  | {
      mode: 'edit'
      customer: Customer
  }

function form({ mode, customer }: Props) {
  const formId = mode === 'edit' ? customer.id : 'foo'
}

据我了解,客户永远不会undefinedmode现在这样edit。我以为这是某种 TypeScript Guard?

操场

标签: typescript

解决方案


推荐阅读