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

164
Visualizações
How to give give two Types as union type to input props in Reactjs typescript

I am developing a isolated component in react js

I Have these two properties as inputs to this component and I am converting these input data into regular Arrays and display them in the UI. Practically any of the property will be the input to this component. If data1 exists then i would like to take data1 and process it . Otherwise data2 . But at a time two inputs wont be exist . thats a requirement.

data1: MyObject<string, Type1>;
data2: MyObject<string, Type2>;

Type1 Structure looks like this

{
    x: string;
    propA: 'a' | 'b' | 'c';
    y: string;
    etc: ...
}

Type 2 Structure will look like this

{
    x: string;
    propB: 'a' | 'b' | 'c';
    y: string;
    etc: ...
}

I have a method where it accepts both types as union and i need to process the data if my input is type 1 then i will take type object property and process it otherwise i need to take type 2 property and process it .

private convertBannerToMessage(message: Type1 | Type2): void {
    const msg = { ...message };
    const msgType = msg.propA ?? msg.propB;

    switch (msgType) {
        case X:
        return this.processData(msg);

        case Y:
        return this.processData(msg);

        case Z:
        return this.processData(msg);

        default:
        return null;
    }
}

I am getting error on accessing propA or propB property .

Property 'propA' does not exist on type '{ id: string; propA: "a" | "b" | "c"; 
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can create a function to check if msg is an instance of Type1/Type2 like this:

function instanceOf<T> (object: any, prop: string): object is T {
    return prop in object;
};
const msgType = instanceOf<Type2>(msg, "template") ? msg.template : msg.messageType;
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