Home > Blockchain >  How to pass object as a parameter for function with optional object fileds in TypeScript?
How to pass object as a parameter for function with optional object fileds in TypeScript?

Time:03-29

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

CodePudding user response:

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)
    })
}
  • Related