首页 > 解决方案 > 我们可以在 getDerivedStateFromError() 中期待什么错误类型?

问题描述

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

标签: reactjstypescript

解决方案


Typescript 有一个Error可以使用的全局接口。

interface Error {
    stack?: string;
}

所以你可以使用

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

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

GetDerivedStateFromError类型如下所示,我认为它的错误类型不应该是 type ,any而且应该是 typeError

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;

推荐阅读