如果检查后,Typescript未检测到定义了可选字段

kmbjn2e3  于 2023-06-30  发布在  TypeScript
关注(0)|答案(1)|浏览(151)

我有像贝娄的代码

async patchMultiple(expenses: PatchExpenseDto[]) {
    const currentExpenses: Required<PatchExpenseDto>[] = []
    const newExpenses: PatchExpenseDto[] = []

    expenses.forEach(expense => {
      if (expense._id) {
        expense._id
        currentExpenses.push(expense) // typescript throw error here
      } else {
        newExpenses.push(expense)
      }
    })
  }

使用if(expense._id)检查后,typescript仍然抛出错误

Argument of type 'PatchExpenseDto' is not assignable to parameter of type 'Required<PatchExpenseDto>'.
  Types of property '_id' are incompatible.
    Type 'ObjectId | undefined' is not assignable to type 'ObjectId'.
      Type 'undefined' is not assignable to type 'ObjectId'
bvuwiixz

bvuwiixz1#

Typescript知道属性实际上存在,但它不能使用if条件推断对象的类型。
你可以使用typeguard来解决这个问题:

interface PatchExpenseDto  {
name : string;
_id? : string;
}
function expenseIsCurrent(expense: PatchExpenseDto): expense is Required<PatchExpenseDto> {
  return expense._id !== undefined;
}



const patchMultiple = (expenses: PatchExpenseDto[]) => {
    const currentExpenses: Required<PatchExpenseDto>[] = []
    const newExpenses: PatchExpenseDto[] = []

    expenses.forEach(expense => {
      if (expenseIsCurrent(expense)) {

        currentExpenses.push(expense) // typescript throw error here
      } else {
        newExpenses.push(expense)
      }
    })
  }

Playground

相关问题