1

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?

1 Answer 1

3

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}/>
    }
  }
}
Sign up to request clarification or add additional context in comments.

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.