我们在getDerivedStateFromError()中可以期望什么错误类型?

时间:2019-05-02 05:25:53

标签: reactjs typescript

根据TypeScript definition,类型为any,而相关方法componentDidCatch()收到类型为Error的错误。为什么会出现这种不一致?

1 个答案:

答案 0 :(得分:3)

Typescript具有一个全局Error界面,您可以使用。

interface Error {
    stack?: string;
}

因此您可以使用

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

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

GetDerivedStateFromError类型如下所示,我认为它的错误类型不应该是any类型,而应该是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;