You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为什么TypeScript会忽略我的undefined检查?

问题原因与解决方案

你的问题出在两次独立调用state.get(action.layer.name),TypeScript无法保证这两次调用返回的是同一个值——比如如果state.get是一个非纯函数(每次调用可能返回不同结果),那第一次判断为非undefined,第二次调用仍可能返回undefined,所以TypeScript不会自动把第二次调用的返回值类型窄化为非undefined。

解决方法:将结果存入变量,只调用一次

把state.get的结果存到一个变量里,后续直接使用这个变量,TypeScript就能跟踪到变量的类型已经被窄化:

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

补充说明

如果state.get是纯函数(相同输入永远返回相同输出),你也可以用非空断言运算符!强制告诉TypeScript这个值不会是undefined,但这种方法不推荐,因为它跳过了TypeScript的类型检查,一旦逻辑变化容易引入bug:

// 不推荐,仅作为备选
if (state.get(action.layer.name) != undefined) {
  return state.get(action.layer.name)!.data.filter(({ id }) => id !== action.item.id);
}

内容的提问来源于stack exchange,提问作者anton

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 18:54:39