Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

156
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!