与 Redux (mapStateToProps) 连接的 ErrorBoundary 组件上的 TypeScript 错误

问题描述

我在 React/ErrorBoundary 组件上遇到了类型问题,指出 类型为“typeof ErrorBoundary”的参数不可分配给类型为“ComponentType的参数从不 >'

Error - Argument of type 'typeof ErrorBoundary' is not assignable to parameter of type 'ComponentType'.

澄清一下:我使用 mapStatetoProps 将其与商店中设置的用户语言首选项相关联。

这是我的组件

interface ErrorTexts {
  texts: ErrorTextType;
}

interface Props {
  children: ReactNode | ReactNode[];
  texts: ErrorTextType;
}

interface State {
  error: Error | null;
}

class ErrorBoundary extends Component<Props,State> {
  static propTypes = {
    children: node,texts: errorTextsPropType
  };

  static defaultProps = {
    children: null,texts: defaultTexts.en.error
  };

  state: State = {
    error: null
  };

  static getDerivedStateFromError(error: Error): State {
    return { error };
  }

  componentDidCatch(error: Error,errorInfo: ErrorInfo) {
    console.error('Something unexpected had happened',error,errorInfo);
  }

  render() {
    const { error }: { error: Error | null } = this.state;
    const { texts }: ErrorTexts = this.props;

    if (error) {
      return <ErrorComponent error={error.message} texts={texts} />;
    }
    return this.props.children;
  }
}

const mapStatetoProps = (state: AppState): ErrorTexts => ({
  texts: state.texts.error
});

export default connect(mapStatetoProps)(ErrorBoundary);

作为参考,这些是我导入的 ErrorText 类型:

export interface ErrorTextType {
  errorLine1: string;
  errorLine2: string;
  notifyMe: string;
  title: string;
}

export const errorTextsPropType = shape({
  errorLine1: string.isrequired,errorLine2: string.isrequired,notifyMe: string.isrequired,title: string.isrequired
});

因此,在母组件上,我遇到了一个错误这个 JSX 标签的“children”属性需要一个类型为“never”的子元素,但提供了多个孩子。

enter image description here

有关如何解决此问题的任何想法? :/

解决方法

不要单独编写接口 Props,而是使用 InferProps 泛型来推断 prop 类型:

import PropTypes,{ shape,InferProps} from "prop-types";

class ErrorBoundary extends Component<InferProps<typeof ErrorBoundary.propTypes>,State> {
  static propTypes = {
    children: PropTypes.node,texts: errorTextsPropType,};