我有像贝娄的代码
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'
1条答案
按热度按时间bvuwiixz1#
Typescript知道属性实际上存在,但它不能使用
if
条件推断对象的类型。你可以使用typeguard来解决这个问题:
Playground