【发布时间】: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