Digamos que tengo esta función en mi API de TypeScript que se comunica con la base de datos.
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) }) } En el bloque de modify , puede ver que verifico qué parámetro se pasó: identificación o correo electrónico.
En código se ve así:
const checkIfEmailUsed = await clientService.getClientByEmailOrId({ email: newEmail })Y aquí está el problema, no puedo hacerlo porque falta un parámetro. Pero lo que necesito es pasarlo así y verificar qué parámetro se pasó.
Por supuesto, puedo hacer esto:
const checkIfEmailUsed = await clientService.getClientByEmailOrId({ email: newEmail, id: null }) Y esto va a funcionar. Pero, ¿existe una solución para no pasarlo así: { email: newEmail, id: null } , pero solo por { email: newEmail } ?
Creo que estás buscando parámetros opcionales. Puede marcar las propiedades de un objeto como opcionales agregando un ? a la declaración de tipo.
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) }) }