Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

211
Vistas
How to define a function with an object with multiple entries as an argument, that only accepts one entry?

Imagine a function that get an object as argument that has two entries with any possible type.

const x = ({a,b}:{a: string, b: string}) => {
    // return something
}

x({a: "foo"}) // OK
x({b: "bar"}) // OK
x({a: "foo", b: "bar"}) // get a compile error in this case!

How can we set this function in a way that only one of the entries be passed to function? In other words, I need to get a compile error when both entries are set inside the function? For example, if "a" is already passed, the moment "b" is also passed we get a compilation error and vice versa.

about 4 years ago · Santiago Gelvez
1 Respuestas
Responde la pregunta

0

My original intuitive, and obviously wrong, answer: Use a union type:

{ a: string } | { b: string }

This will not trigger a compile error for x({a: "foo", b: "bar"}).

Working solution: You can follow this advice for “mutually exclusive types”:

type Without<T, U> = { [P in Exclude<keyof T, keyof U>]?: never };
type XOR<T, U> = (T | U) extends object ? (Without<T, U> & U) | (Without<U, T> & T) : T | U;

const x = (args: XOR<{ a: string }, { b: string }>) => {
    // return something
}

x({a: "foo"}) // OK
x({b: "bar"}) // OK
x({a: "foo", b: "bar"}) // get a compile error in this case!

See TypeScript Playground

about 4 years ago · Santiago Gelvez Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda