如何使用 Typescript 在 React 错误边界中允许回退道具?

问题描述

我的应用程序顶部有一个错误边界。它有效,我可以将自定义组件作为后备传递给它。但是,Typescript 声称:

属性 'fallback' 在类型 'Readonly & Readonly' (errorboundary.js)

还有那个

没有与此调用匹配的过载。 (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;
  }
}

如何解决这个问题?

请注意,我没有使用 react-error-boundary 库。本机错误边界类应该可以完成这项工作。

编辑:完整的工作代码

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

解决方法

你应该扩展 Component 传递你的 props 的类型定义,像这样:

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

interface ErrorBoundaryState {
  error: boolean | null;
}

export class ErrorBoundary extends React.Component<ErrorBoundaryProps,ErrorBoundaryState> { ... }