Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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)
    })
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!