Typescript 字典上出现奇怪错误“对象可能“未定义”

Typescript 字典上出现奇怪错误“对象可能“未定义”,typescript,Typescript,在下面的代码中,为什么stopsDict[first].directions.pushtest;行通过检查但未通过StopDict[stopName].directions.pushtest;一个 接口停止{ [键:字符串]:停止; } 接口停止{ 方向?:字符串[]; } 让stopsDict:stopsDict={ 第一:{ 说明:[] }, 第二:{} }; if Array.isArraystopsDict[first].方向{ stopsDict[first].directions.p

在下面的代码中,为什么stopsDict[first].directions.pushtest;行通过检查但未通过StopDict[stopName].directions.pushtest;一个

接口停止{ [键:字符串]:停止; } 接口停止{ 方向?:字符串[]; } 让stopsDict:stopsDict={ 第一:{ 说明:[] }, 第二:{} }; if Array.isArraystopsDict[first].方向{ stopsDict[first].directions.pushtest;//确定 } 让stopName=first; if Array.isArraystopsDict[stopName].方向{ stopsDict[stopName].directions.pushtest;//错误TS2532:对象可能是“未定义的”。 } 因为stopsDict[name].directions在理论上可能为空。您可以告诉TS您更清楚,并承担所有责任,如果不是:

stopsDict[name].directions!.push("test")
对于非玩具示例,您可能希望引入确保满足前提条件的检查,而不是通过类型检查器强制执行

看更多

具体而言,这不会引发错误:

let dirs = stopsDict[stopName].directions;
if (Array.isArray(dirs)) {
  dirs.push("test");
}

第二个答案的可能重复比公认的答案要好。谢谢,这确实是同样的问题。底线:我需要编写类似于stopsDict[stopName]的内容。方向为字符串[]。如果我刚刚检查了stopsDict[stopName],则pushtest事件。方向是前一行的数组。我编辑了代码,以显示即使我检查了stopsDict[stopName],错误仍然存在.direction是一个数组,因此stopName不能为null。TS不记得从一个表达式到下一个表达式的检查。设dirs=stopsDict[stopName]。方向;如果Array.isArraydirs{dirs.push…未引发错误。