简体   繁体   中英

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.

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.

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 } ?

I think you are looking for optional parameters. You can mark properties of an object as optional by adding an ? 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)
    })
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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