简体   繁体   English

如何将 object 作为 function 的参数传递给 TypeScript 中可选的 object 字段?

[英]How to pass object as a parameter for function with optional object fileds in TypeScript?

Let's say I have this function in my TypeScript API that communicates with database.假设我的 function 在与数据库通信的 TypeScript API 中。

export const getClientByEmailOrId = async (data: { email: any, id: any }) => {
  return knex(tableName)
    .first()
    .modify((x: any) => {
      if (data.email) x.where('email', data.email)
      else x.where('id', data.id)
    })
}

In modify block you can see that I check what param was passed - id or email.modify块中,您可以看到我检查了传递的参数 - id 或 email。

In code it looks like this:在代码中它看起来像这样:

const checkIfEmailUsed = await clientService.getClientByEmailOrId({ email: newEmail })

And here is the problem, I can't do that because of missing parameter.这就是问题所在,由于缺少参数,我无法做到这一点。 But what I need, is to pass it like this, and check what param was passed.但我需要的是像这样传递它,并检查传递了什么参数。

Of course, I can just do this:当然,我可以这样做:

const checkIfEmailUsed = await clientService.getClientByEmailOrId({ email: newEmail, id: null })

And this going to work.这将起作用。 But does exist solution not to pass it like this: { email: newEmail, id: null } , but just by { email: newEmail } ?但是否存在不通过这样的解决方案: { email: newEmail, id: null } ,而只是通过{ email: newEmail }

I think you are looking for optional parameters.我认为您正在寻找可选参数。 You can mark properties of an object as optional by adding an ?您可以通过添加?将 object 的属性标记为可选。 to the type declaration.到类型声明。

type Data = {
  email: any,
  id?: any // <= and notice the ? here this makes id optional
}

export const getClientByEmailOrId = async (data: Data) => {
  return knex(tableName)
    .first()
    .modify((x: any) => {
      if (data.email) x.where('email', data.email)
      else x.where('id', data.id)
    })
}

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

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