typescript - 为什么当我将对象显式包装在 `if` 中时,TS 会提示对象可能为空?

标签 typescript

这是我的代码:

import React from 'react';

export default class ErrorBoundary extends React.Component {

    state = {error: null, errorInfo: null};

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

    render() {
        if (this.state.errorInfo) {
            return (
                <div>
                    <h2>Something went wrong.</h2>
                    <pre>
                        <code>
                            {String(this.state.error)}
                            {this.state.errorInfo.componentStack} // <-- error is here
                        </code>
                    </pre>
                </div>
            );
        }

        return this.props.children;
    }
}

讯息是:

ERROR in [at-loader] ./src/components/ErrorBoundary.tsx:22:30 TS2531: Object is possibly 'null'.



enter image description here

但是if如果 this.state.errorInfo,块将不会执行是 null ,所以我不确定是什么问题。

为什么我会收到此错误以及如何修复它?

即使我这样写:
 {this.state.errorInfo !== null ? this.state.errorInfo.componentStack : 'hello'}

或者
 {this.state && this.state.errorInfo ? this.state.errorInfo.componentStack : 'hello'}

我犯了同样的错误。

tsconfig 很好的衡量标准:
{
    "compilerOptions": {
        "strict": true,
        "importHelpers": false,
        "inlineSources": true,
        "noEmitOnError": true,
        "pretty": true,
        "module": "ES6",
        "noImplicitAny": true,
        "suppressImplicitAnyIndexErrors": false,
        "removeComments": true,
        "preserveConstEnums": false,
        "sourceMap": true,
        "lib": ["es2018","dom"],
        "skipLibCheck": true,
        "outDir": "dist",
        "target": "es2018",
        "declaration": true,
        "resolveJsonModule": false,
        "esModuleInterop": false,
        "jsx": "react",
        "moduleResolution": "node",
        "allowSyntheticDefaultImports": true
    },
    "files": [
        "src/index.tsx"
    ],
    "include": [
        "src/types/**/*.d.ts"
    ],
    "exclude": [
        "node_modules"
    ]
}

最佳答案

看起来

state = {error: null, errorInfo: null};

覆盖 state的类型。 errorInfo 的推断类型始终为 null您可以通过明确给出类型来纠正它:
state: { error: Error | null, errorInfo: React.ErrorInfo | null } =
{ error: null, errorInfo: null };

此问题在此处报告和讨论 https://github.com/Microsoft/TypeScript/issues/10570

关于typescript - 为什么当我将对象显式包装在 `if` 中时,TS 会提示对象可能为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52597035/

相关文章:

angular - 带有 Angular 的 Webpack 别名 - 不能使用命名空间 'UtilsService' 作为类型

typescript - ts(2339) 类型 'ariaLabel' 上不存在属性 'HTMLElement'

javascript - typescript :在类型 'string' A 上找不到参数类型为 '{ "的索引签名“:字符串;}

javascript - 如何使用 typescript 编写 vuex 存储?

javascript - JSX TypeScript 定义覆盖自定义框架的组件?

javascript - typescript 获得函数内的当前范围或变量()

javascript - 像 jQuery 位置方法一样获取 Angular 中的位置

generics - TypeScript 泛型传递枚举

javascript - 如何在 JsSIP 中处理音频流?

javascript - 在 typescript Jest 上下文中, Node 配置配置是 `undefined` 吗?