简体   繁体   English

解构Typescript中的function参数

[英]Destructuring function parameters in Typescript

So I have this little function that takes care of updating a todo document in the database, it looks like so所以我有这个小 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
  }

The id property is meant to come from the req.params object, and the ...todoInfo comes from the req.body object. id属性来自 req.params object,而...todoInfo来自 req.body object。 But typescript throws an error that property id does not exist on interface ITodo .但是 typescript 会抛出一个错误,即property id does not exist on interface ITodo How do I overcome this issue?我该如何克服这个问题? The interface ITodo looks like this currently,目前ITodo的界面是这样的,

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...}}我尝试了这种方法,但它导致 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
  }

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.我不想将属性id添加到接口,因为它要么我一直在到处使用它,要么我可以使它成为可选的,这会弄乱其他 function 调用,因为id属性不能未定义。 Thank you very much.非常感谢。

You can use an intersection type:您可以使用交叉点类型:

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

Playground Link 游乐场链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM