【问题标题】:React hoc Generic error - could be instantiated with a different subtype of constraint 'InjectedProps'React hoc Generic 错误 - 可以用不同的约束子类型“InjectedProps”实例化
【发布时间】:2021-06-26 07:48:12
【问题描述】:

为了理解问题,我已将示例精简到最低限度:

示例代码 - Hoc.tsx

import React, { FC, ComponentType } from 'react';
import { connect } from 'react-redux';

interface ReduxProps {
  param: string;
}

interface InjectedProps {
  str: string;
}

const withWrapper = <P extends InjectedProps>(Comp: ComponentType<P>) => {
  const Wrapper: FC<ReduxProps> = ({ param }) => {
    // do sometthing with param
    // inject property
    const str = 'hello';
    return <Comp str={str} />;
  };
  Wrapper.displayName = 'Wrapper';

  // removed actual state to show example to test in typescript playground
  const mapStateToProps = () => ({
    param: 'some param'
  });

  const connector = connect(mapStateToProps);
  return connector(Wrapper);
};

export default withWrapper;

在打字稿游乐场我得到这个错误:

错误

类型 '{ str: 字符串; }' 不可分配给类型 'P'。 '{str:字符串; }' 可分配给“P”类型的约束,但“P”可以用约束“InjectedProps”的不同子类型来实例化

如何将 props 注入我的高阶组件并保留提供的泛型?

【问题讨论】:

    标签: reactjs typescript higher-order-components


    【解决方案1】:

    这有点笨拙,但找到了解决方案

    import React, { FC, ComponentType } from 'react';
    import { connect } from 'react-redux';
    
    interface ReduxProps {
      param: string;
    }
    
    interface InjectedProps {
      str: string;
    }
    
    const withWrapper = <P extends {}>(Comp: ComponentType<P | InjectedProps>) => {
      const Wrapper: FC<ReduxProps> = ({ param }) => {
        // do sometthing with param
        // inject property
        const str = 'hello';
        return <Comp str={str} />;
      };
      Wrapper.displayName = 'Wrapper';
    
      // removed actual state to show example to test in typescript playground
      const mapStateToProps = () => ({
        param: 'some param'
      });
    
      const connector = connect(mapStateToProps);
      return connector(Wrapper);
    };
    
    export default withWrapper;
    
    interface Props {
      something: string;
    }
    const ConsumeWith: FC<Props | InjectedProps> = props => {
      const str = (props as InjectedProps).str;
      const something = (props as Props).something;
    
      return (
        <div>
          {str}{something}
        </div>
      );
    };
    
    const Final = withWrapper<Props>(ConsumeWith);
    
    

    【讨论】:

      猜你喜欢
      • 2021-11-24
      • 2021-08-14
      • 1970-01-01
      • 2020-01-22
      • 2021-02-13
      • 2020-03-27
      • 2019-12-13
      • 2021-10-14
      • 2021-12-10
      相关资源
      最近更新 更多