0

So I have this little function that takes care of updating a todo document in the database, it looks like so

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 property is meant to come from the req.params object, and the ...todoInfo comes from the req.body object. But typescript throws an error that property id does not exist on interface ITodo. How do I overcome this issue? The interface ITodo looks like this currently,

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

I tried this method, but it led to object nesting like so.. {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 property id to the interface because it's either I keep using it everywhere or I could make it optional which will mess up other function calls because the id property cannot be undefined. Thank you very much.

1 Answer 1

2

You can use an intersection type:

async function update({ id, ...todoInfo }: { id: string } & ITodo) {
    //...     
}

Playground Link

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.