4

Is there a way in React to separate the props object based on an Typescript interface which extends multiple other interfaces? The other way I see, is to pass duplicate props to components that won't use them which is not the optimal solution.

interface IProps extends IAProps, IBProps {}

const Component1: SFC<IProps> = (props) => 
   return (
     <Component2
         {...props} <--- only IAProps
     />
     <Component3
         {...props} <--- only IBProps
     />
  );
}

3 Answers 3

13

You can use the & to merge interfaces. Such as <ScreenProps extends {} & SliderProps & ReactNavigationProps>

Example:


interface AProps {
  testa: any
}

interface BProps {
  testb: any
}


class Test extends Component<AProps & BProps> {
  // ...
}


// or


<IProps extends AProps & BProps>

class Test extends Component<IProps> {
   // ...
}


Sign up to request clarification or add additional context in comments.

Comments

3

if you want your component to accept any type of props based on interfaces you can do this:

const Component1: SFC<IAProps & IBProps> = (props) => 
       return (
         <Component2
             {...props} <---IAProps
         />
         <Component3
             {...props} <--- IBProps
         />
      );
    }

Note that: if not your all props are required, you can use the optional props in each interface as the following:

interface  IAProps {
    name: string; // required
    age?: number; //optional 

}

or if your all interface's pops should be marked as required but you still want to not use all of them in your component you can do this:

const Component1: SFC<Partial<IAProps> & Partial<IBProps>> = (props) => 
       return (
         <Component2
             {...props} <---IAProps
         />
         <Component3
             {...props} <--- IBProps
         />
      );
    }

something to mention, that Partial will mark all your interface's props as optional

Comments

-1

I think the simple approach of just passing two different props is a clean solution:

interface IProps {
    a: IAProps;
    b: IBProps;
}

const Component1: SFC<IProps> = (props) => 
   return (
     <Component2
         {...props.a} <--- only IAProps
     />
     <Component3
         {...props.b} <--- only IBProps
     />
  );
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.