TypeScript error on an ErrorBoundary component connected with Redux (mapStateToProps)

1.8k Views Asked by At

I'm facing a type issue on an React/ErrorBoundary component, stating that Argument of type 'typeof ErrorBoundary' is not assignable to parameter of type 'ComponentType< never >'.

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

Just to clarify: I use mapStateToProps to connect it with user's language preferences set on store.

Here's my component

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);

For reference, these are my imported ErrorText types:

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
});

Accordinly, on the mother component, I've got an error This JSX tag's 'children' prop expects a single child of type 'never', but multiple children were provided.

enter image description here

Any ideas on how to solve this issue? :/

1

There are 1 best solutions below

0
On

Instead of writing the interface Props separately, use InferProps generic to infer the prop type:

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

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