对象可能是‘未定义’

对象可能是‘未定义’

本文介绍了打字稿“错误 TS2532:对象可能是‘未定义’";即使经过未定义的检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 tsc 上使用 --strict 选项,但我遇到了以下我似乎不明白的奇怪"情况.

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.

如果我写:

function testStrict(input: {query?: {[prop: string]: string}}) {
  if (input.query) {
    Object.keys(input.query).forEach(key => {
      input.query[key];
    })
  }
  return input;
}

编译器抱怨:

test.ts(5,9):错误 TS2532:对象可能是未定义".

(违规行是 input.query[key];)

我不明白的是,我已经在函数if (input.query)的第一行用ifguard检查了undefined,那么为什么编译器认为它可能是未定义的?

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?

我通过在对象访问之前添加另一个相同的守卫来解决这个问题,例如:

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.

推荐答案

因为第二次访问 input.query 发生在另一个函数内部,箭头函数传入 forEach.流分析不会跨越函数边界,因此由于您在另一个函数中,您需要再次测试.

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.

双重测试的替代方法是使用局部变量,因为变量的类型在赋值时被锁定,并且不会包含 undefined 类型:

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 :

function testStrict(input: { query?: { [prop: string]: string } }) {
    if (input.query) {
        const query = input.query;
        Object.keys(input.query).forEach(key => {
            query[key];
        })
    }
    return input;
}

这篇关于打字稿“错误 TS2532:对象可能是‘未定义’";即使经过未定义的检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 11:40