【问题标题】:Why is Typescript ignoring my check for 'undefined'?为什么 Typescript 会忽略我对“未定义”的检查?
【发布时间】:2022-08-15 03:21:10
【问题描述】:

即使我检查我的对象是否不是undefined TS 也在抱怨。

我的代码示例:

if (state.get(action.layer.name) != undefined) {
   return state.get(action.layer.name).data.filter(({ id }) => id !== action.item.id);
}

TS 说:

Object is possibly \'undefined\'.ts(2532)

我做错了什么?

标签: typescript


【解决方案1】:

即使从state.get(action.layer.name) 返回的内容不是未定义的,它也不能保证返回的内容具有data 属性,因此Object.data 将是未定义的。

也许你可以尝试检查

if (state.get(action.layer.name).data !== undefined) {
   return state.get(action.layer.name).data.filter(({ id }) => id !== action.item.id);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-03
    • 2020-08-29
    • 1970-01-01
    • 2017-01-16
    • 1970-01-01
    • 2014-07-10
    • 1970-01-01
    • 2017-04-16
    相关资源
    最近更新 更多