首页 > 解决方案 > 'string'.ts 类型上不存在属性'componentStack'

问题描述

我正在使用 Typescript 和 React 实现 ErrorBoundary

TSLint 显示错误Property 'componentStack' does not exist on type 'string'

这是我的代码实现

interface IState {
  info: ErrorInfo;
}

  public state = {
    errorInfo: "",
  };

  public componentDidCatch(error: Error, errorInfo: ErrorInfo) {
    this.setState({
      errorInfo
    });
  }
  public render() {
    if (this.state.errorInfo) {
      return (
          <p>
            {this.state.errorInfo.componentStack}
          </p>
      );
    }
  }

标签: reactjstypescripttypescript-generics

解决方案


您在这里隐式声明errorInfo为字符串:

public state = {
    errorInfo: "",
};

因此,打字稿中存储的errorInfo内容是string. componentStack不能存在,string这就是你得到错误的原因。

您应该声明如下内容:

public state: {
   errorInfo: string | { componentStack: Function, },
} = {
    errorInfo: "",
};

并完成对state对象内部内容的描述。

或者any如果您不知道,请使用。

public state: any = {
    errorInfo: "",
};

无论如何,你应该componentStack在调用它之前测试它是否存在,以防errorInfo它确实是一个空的string.

if (this.state.errorInfo && typeof this.state.errorInfo.componentStack === 'Function') {
    {this.state.errorInfo.componentStack}
}

推荐阅读