Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

179
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda