首页 > 解决方案 > 用于识别总是评估的 if 分支的编译器规则

问题描述

在这段代码中:

class Abc {
    field1: string;

    constructor(data: string) {
        if (true) {
            this.field1 = "";
        }
    }

}

没有编译器错误。

但是如果我将if条件中的表达式更改为data !== null,则会出现编译器错误:Property 'field1' has no initializer and is not definitely assigned in the constructor。但是从编译器的角度来看,datatype ofstring永远不应该是 null,那只能是string | null. 为什么编译器会给出这个错误?

标签: typescript

解决方案


推荐阅读