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

158
Vistas
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 Respuestas
Responde la pregunta

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