0

I have an error boundary on top of my app. It works, and I can pass it a custom component as a fallback. However, Typescript claims that:

Property 'fallback' does not exist on type 'Readonly<{}> & Readonly<{ children?: ReactNode; }>' (errorboundary.js)

and that

No overload matches this call. (index.tsx)

import { Component } from "react";

export class ErrorBoundary extends Component {
  state = { error: null };

  static getDerivedStateFromError(error) {
    return { error };
  }

  render() {
    if (this.state.error) {
      return this.props.fallback;
    }
    return this.props.children;
  }
}

How to fix this?

Please note I'm not using the react-error-boundary library. The native error boundary class should do the work.

EDIT: complete working code:

interface Props {
  fallback: React.ReactNode;
}

export class ErrorBoundary extends Component<Props> {
  state = { error: null };

  static defaultProps: Props = {
    fallback: [],
  };

  static getDerivedStateFromError(error) {
    return { error };
  }

  render() {
    if (this.state.error) {
      return this.props.fallback;
    }
    return this.props.children;
  }
}

1 Answer 1

3

You should extend Component passing the type definition of your props, like this:

interface ErrorBoundaryProps {
  fallback: JSX.Element; // if fallback is a JSX.Element
}

interface ErrorBoundaryState {
  error: boolean | null;
}

export class ErrorBoundary extends React.Component<ErrorBoundaryProps, ErrorBoundaryState> { ... }
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, and also declare the static defaultProps in the class. I've edited the question with the full working code.

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.