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

125
Visualizações
Typescript overload interface attribute

Imagine I have a bunch of payload options like:

interface IOne {
  type: 'One',
  payload: {
    name: string,
    age: number
  }
}

interface ITwo {
  type: 'Two',
  payload: string
}

declare type TBoth = IOne | ITwo;

So I can receive one of the two above as parameter. I want the typescript to be able to recognize the parameters of each type when using a switch for example.

The problem I'm having is when I'm trying to Create the object.

const value = req.body?.message; // just an example
const test: TBoth = {
  type: value ? 'One' : 'Two,  // <--- Now it should autocomplete/suggest the rights parameters based on this attribute.
}

I get:

Types of property 'type' are incompatible. Type '"One" | "Two"' is not assignable to type '"Two"'.

Is it possible?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can narrow the types of discriminated unions like this:

const doSomething = (test: TBoth) => {
  if(test.type === `One`) {
    // hover the below `test` with VSCode you will see:
    //   (parameter) test: IOne
    handleIOne(test)
  } else {
    // hover the below `test` with VSCode you will see:
    //   (parameter) test: ITwo
    handleITwo(test)
  }
}

See a live example

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