简体   繁体   English

打字稿 - 动态扩展界面

[英]Typescript - Dynamically extend interface

I am trying to type an existing React Native module with the following props: 我试图用以下道具键入现有的React Native模块:

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. 我有一个组件1和2的接口,但是,我无法扩展它们,因为道具是由哪个组件使用决定的。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM