TypeScript中解构函数参数

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对象,…todoInfo来自req.body对象。但是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
}

我尝试过这个方法,但它导致了像这样的对象嵌套。。{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属性添加到接口中,因为它要么是我在任何地方都使用它,要么是我可以使它成为可选的,这会使其他函数调用陷入混乱,因为id属性不能是未定义的。非常感谢你。

猜你喜欢

转载自blog.csdn.net/diaojw090/article/details/114011220
今日推荐