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

174
Visualizações
Typescript Interface to contain a non-mandatory property or another

I know that there are similar questions here but mine is a little different.

There is an Interface that can have one or another property, let's call them black and white they aren't mandatory, so the Interface is valid without them and it is valid with one of them.

Good:

interface MyInterface {
  name: string;
}

Good:

interface MyInterface {
  name: string;
  black?: boolean;
}

Good:

interface MyInterface {
  name: string;
  white?: boolean;
}

Bad: (or it could be Good if we can check that maximum one of either black or white is there)

interface MyInterface {
  name: string;
  black?: boolean;
  white?: boolean;
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Because TypeScript is structurally-typed, it is not an error for an object to have excess properties, unless you explicitly disallow this by setting the property's optional type to never, like this:

TS Playground

type BlackOptional = {
  black?: boolean;
  white?: never;
};

type WhiteOptional = {
  black?: never;
  white?: boolean;
};

type Name = {
  name: string;
}

type Example = (Name & BlackOptional) | (Name & WhiteOptional);

const example1: Example = { /*
      ^^^^^^^^
Types of property 'black' are incompatible. Type 'boolean' is not assignable to type 'never'.(2322) */
  name: 'name',
  black: true,
  white: true,
};

const example2: Example = {
  name: 'name',
  black: true,
};

const example3: Example = {
  name: 'name',
  white: true,
};
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