【问题标题】:Strange error "Object is possibly 'undefined'" on a dictionary字典上的奇怪错误“对象可能是'未定义'”
【发布时间】:2019-09-26 18:07:20
【问题描述】:

在下面的代码中,为什么stopsDict["first"].directions.push("test"); 行通过了检查,而stopsDict[stopName].directions.push("test"); 没有通过检查?

interface StopsDict {
  [key: string]: Stops;
}

interface Stops {
  directions?: string[];
}

let stopsDict: StopsDict = { 
  first: {
    directions: []
  },
  second: {}
};

if (Array.isArray(stopsDict["first"].directions)) {
  stopsDict["first"].directions.push("test"); //OK
}

let stopName = "first";
if (Array.isArray(stopsDict[stopName].directions)) {
  stopsDict[stopName].directions.push("test"); //error TS2532: Object is possibly 'undefined'.
}

【问题讨论】:

  • Typescript: Object is possibly 'undefined' 的可能重复项(第二个答案比接受的更好)
  • 谢谢,这确实是同一个问题。底线:如果我刚刚检查 stopsDict[stopName].directions 是前一行的数组,我需要编写类似 (stopsDict[stopName].directions as string[]).push("test") 的事件。

标签: typescript


【解决方案1】:

因为理论上stopsDict[name].directions 可以是null。你可以告诉 TS 你知道得更清楚,如果不知道,你可以承担所有责任:

stopsDict[name].directions!.push("test")

对于一个非玩具示例,您可能希望引入检查以确保满足先决条件,而不是通过类型检查器进行暴力破解。

查看更多in docs。

具体来说,这不会引发错误:

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

【讨论】:

  • 我已经编辑了代码以显示即使我检查了stopsDict[stopName].direction is an array(因此stopName 不能为空),错误仍然存​​在。
  • TS 不记得从一个表达式到下一个表达式的检查。 let dirs = stopsDict[stopName].directions; if (Array.isArray(dirs)) { dirs.push... 不会引发错误。
猜你喜欢
  • 2022-01-05
  • 1970-01-01
  • 1970-01-01
  • 2021-10-07
  • 2021-12-29
  • 2020-12-01
  • 2012-08-23
  • 2021-03-11
  • 1970-01-01
相关资源
最近更新 更多