Destructuring function parameters in 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
  }

The id attribute means from the req.params object,...todoInfo comes from the req.body object. But typescript throws an error property id does not exist on interface ITodo. How can I overcome this problem? The interface ITodo now looks like this,

export interface ITodo {
  todo_name: string
  start_time: Date
  end_time: Date
  description: string
  priority: Priority
}

I tried this method, but it resulted in object nesting like this. . {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
  }

I don’t want to add the id attribute to the interface, because it’s either I use it everywhere, or I can make it optional, which will mess up other function calls because the id attribute cannot be undefined . thank you very much.

Guess you like

Origin blog.csdn.net/diaojw090/article/details/114011220