I am trying to type an existing React Native module with the following props:
useComponent1: boolean
useComponent2: boolean
With the following implementation
render(){
if(useComponent1){
return <Component1 {...props}/>
}
if(useComponent2){
return <Component2 {...props}/>
}
}
I have an interface for components 1 & 2, however, I can't extend both as the props are determined by which component is utilised.
Is it possible to dynamically extends an interface?
If not, is there another solution to this issue?
There can be intersection/union type:
interface Component1Props { .... }
interface Component2Props { .... }
interface WrapperOwnProps {
useComponent1: boolean
useComponent2: boolean
}
type WrapperProps = WrapperOwnProps & (Component1Props | Component2Props);
Props type can be additionally asserted:
class Wrapper extends Component<WrapperProps> {
render(){
const { useComponent1, useComponent2, ...props } = this.props;
if(useComponent1){
return <Component1 {...props as Component1Props}/>
}
if(useComponent2){
return <Component2 {...props as Component2Props}/>
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.