Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What error type can we expect in getDerivedStateFromError()?

According to the TypeScript definition the type is any, whereas the related method componentDidCatch() receives an error of type Error. Why this inconsistency?

like image 503
Naresh Avatar asked May 02 '19 05:05

Naresh


1 Answers

Typescript has a global Error interface that you can use.

interface Error {
    stack?: string;
}

so you can use

static getDerivedStateFromError(error: Error) {
  // ...
}

componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
  // ...
}

the GetDerivedStateFromError type is shown below and I think it's error type should not be of type any, but also of type Error

type GetDerivedStateFromError<P, S> =
        /**
         * This lifecycle is invoked after an error has been thrown by a descendant component.
         * It receives the error that was thrown as a parameter and should return a value to update state.
         *
         * Note: its presence prevents any of the deprecated lifecycle methods from being invoked
         */
        (error: any) => Partial<S> | null;
like image 66
Gabriel Vasile Avatar answered Nov 10 '22 12:11

Gabriel Vasile