英文:
Typescript does not detect optional field is define after check by if
问题
async patchMultiple(expenses: PatchExpenseDto[]) {
const currentExpenses: Required<PatchExpenseDto>[] = []
const newExpenses: PatchExpenseDto[] = []
expenses.forEach(expense => {
if (expense._id) {
expense._id
currentExpenses.push(expense) // typescript在这里报错
} else {
newExpenses.push(expense)
}
})
}
经过检查,即使在if(expense._id)
后,typescript依然报错:
类型“PatchExpenseDto”的参数不能赋给类型“Required<PatchExpenseDto>”的参数。
属性“_id”的类型不兼容。
类型“ObjectId | undefined”不能赋给类型“ObjectId”。
类型“undefined”不能赋给类型“ObjectId”。
英文:
I have the code like bellow
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)
}
})
}
After check with if(expense._id)
typescript still throw the error
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
得分: 1
Typescript理解该属性实际上存在,但无法推断使用if
条件的对象的类型。
您可以使用类型保护来解决此问题:
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)
}
})
}
英文:
Typescript understands that the property in fact exists, but it cannot infer the type of the object using the if
condition.
You can use a typeguard to get past this:
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)
}
})
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论