typescript 即使在未定义检查之后打字稿“错误 TS2532:对象可能是‘未定义’”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49610779/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Typescript "error TS2532: Object is possibly 'undefined'" even after undefined check
提问by Marco
I'm trying to use the --strict
option on tsc
but I ran into the following "weird" case that I don't seem to understand.
我正在尝试使用该--strict
选项,tsc
但遇到了以下我似乎不明白的“奇怪”案例。
If I write:
如果我写:
function testStrict(input: {query?: {[prop: string]: string}}) {
if (input.query) {
Object.keys(input.query).forEach(key => {
input.query[key];
})
}
return input;
}
the compiler complains about:
编译器抱怨:
test.ts(5,9): error TS2532: Object is possibly 'undefined'.
test.ts(5,9): 错误 TS2532: 对象可能是“未定义”。
(the offending line is input.query[key];
)
(违规行是input.query[key];
)
What I don't understand is, I have already checked for undefined with the if guard on the first line of the function if (input.query)
, so why does the compiler think it could possibly be undefined?
我不明白的是,我已经用函数第一行的 if 保护检查了 undefined if (input.query)
,那么为什么编译器认为它可能是 undefined 呢?
I fixed this by adding another identical guard before the object access, like:
我通过在对象访问之前添加另一个相同的保护来解决这个问题,例如:
function testStrict(input: {query?: {[prop: string]: string}}) {
if (input.query) {
Object.keys(input.query).forEach(key => {
if (input.query) {
input.query[key];
}
})
}
return input;
}
but I don't understand why another identical line would be required.
但我不明白为什么需要另一条相同的线路。
采纳答案by Titian Cernicova-Dragomir
Because the second access to input.query
happens inside another function the arrow function passed in to forEach
. Flow analysis does not cross function boundaries, so since you are in another function you need to test again.
因为第二次访问input.query
发生在另一个函数内部,所以箭头函数传入forEach
. 流分析不会跨越函数边界,因此由于您在另一个函数中,您需要再次测试。
An alternative to the double test would be to use a local variable, since the type of the variable is locked in on assignment and it will not include the undefined
type :
双重测试的替代方法是使用局部变量,因为变量的类型在赋值时被锁定,并且不会包含undefined
类型:
function testStrict(input: { query?: { [prop: string]: string } }) {
if (input.query) {
const query = input.query;
Object.keys(input.query).forEach(key => {
query[key];
})
}
return input;
}