【问题标题】:typescript Object is possibly undefined in similar casestypescript Object 在类似情况下可能未定义
【发布时间】:2022-07-10 23:06:51
【问题描述】:
type Person = {
    account?: {
        money: number
    }
}

const person: Person = {}

// case1 - this is not error
if (person.account?.money === 0) {
    console.log("I have no money");
}

// case2 - Object is possibly 'undefined'.(2532)
if (person.account?.money > 0) {
    console.log("I have money!!");
}

为什么打字稿在案例 1 上不显示错误,而只在案例 2 上显示错误?
有什么区别?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    您不能对选项变量进行数学比较。

    【讨论】:

      猜你喜欢
      • 2012-10-21
      • 1970-01-01
      • 2019-03-30
      • 2020-08-11
      • 2016-03-15
      • 2012-09-27
      • 2022-11-15
      • 2013-08-21
      • 2023-03-17
      相关资源
      最近更新 更多