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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:19:40  来源:igfitidea点击:

Typescript "error TS2532: Object is possibly 'undefined'" even after undefined check

typescripttypingtsc

提问by Marco

I'm trying to use the --strictoption on tscbut 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.queryhappens 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 undefinedtype :

双重测试的替代方法是使用局部变量,因为变量的类型在赋值时被锁定,并且不会包含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;
}