Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React prop separation based on multiple Typescript interfaces

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
     />
  );
}
like image 802
Pedro Romano Barbosa Avatar asked Oct 16 '25 08:10

Pedro Romano Barbosa


2 Answers

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> {
   // ...
}


like image 130
cusspvz Avatar answered Oct 18 '25 21:10

cusspvz


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

like image 45
sh.alawneh Avatar answered Oct 18 '25 23:10

sh.alawneh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!