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

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

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