![](/img/trans.png)
[英]Typed function parameters using destructuring and rest in TypeScript
[英]Destructuring function parameters in Typescript
所以我有這個小 function 負責更新數據庫中的待辦事項文檔,看起來像這樣
async function update({id, ...todoInfo }: ITodo) { // this line here
const db = await makeDb()
const foundTodo = await db.collection('todos').updateOne({ _id: transformId(id) }, { $set: { ...todoInfo } })
return foundTodo.modifiedCount > 0 ? { _id: id, ...todoInfo } : null
}
id
屬性來自 req.params object,而...todoInfo
來自 req.body object。 但是 typescript 會拋出一個錯誤,即property id does not exist on interface ITodo
。 我該如何克服這個問題? 目前ITodo的界面是這樣的,
export interface ITodo {
todo_name: string
start_time: Date
end_time: Date
description: string
priority: Priority
}
我嘗試了這種方法,但它導致 object 像這樣嵌套.. {todoInfo: {todo_name...}}
async function update({id, ...todoInfo }: {id: string, todoInfo: ITodo}) {
const db = await makeDb()
const foundTodo = await db.collection('todos').updateOne({ _id: transformId(id) }, { $set: { ...todoInfo } })
return foundTodo.modifiedCount > 0 ? { _id: id, ...todoInfo } : null
}
我不想將屬性id
添加到接口,因為它要么我一直在到處使用它,要么我可以使它成為可選的,這會弄亂其他 function 調用,因為id
屬性不能未定義。 非常感謝。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.