Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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)
    })
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading