How to give give two Types as union type to input props in Reactjs typescript

Viewed 105

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"; 
1 Answers

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