【问题标题】:Why can't the typescript compiler work out that my variables aren't undefined为什么 typescript 编译器不能计算出我的变量不是未定义的
【发布时间】:2023-01-18 21:11:21
【问题描述】:

只是作为这个问题的序言 - 我可能错过了一些东西:)

我有以下代码:

function test(a: number | undefined, b: number | undefined) {
  if (!a && !b) {
    console.log('Neither are present');
    return;
  }

  if (!b && !!a) {
    console.log('b is not present, we only found a - do a thing with a');
    return;
  }

  if (!a && !!b) {
    console.log('a is not present, we only found b - do a thing with b');
    return;
  }

  // At this point, I'd like the compiler to know that both a and b are not undefined,
  // but it doesn't.
  console.log(a + b);
}

编译器在最后一行出现错误消息 'a' is possibly 'undefined''b' is possibly 'undefined'

但是,如果 ab 都存在(即未定义),代码就不可能达到这一点。

我的 if 语句比您预期的更复杂(即我有 !a && !!b 而不仅仅是 !a),因为如果其他参数不存在,我想使用现有参数。

我错过了什么,是否有更多类型化的方式来编写此逻辑?

谢谢。

【问题讨论】:

    标签: typescript


    【解决方案1】:

    问题在于,孤立地看时,没有一个 if 语句实际上缩小了类型。它需要同时考虑多个 if 语句来推断类型已经缩小;对你我来说很简单,但对打字稿来说却不是那么简单。

    即,在第一个if语句之后,ab仍然是number | undefined;他们的类型没有任何改变。这两个变量具有相关性,但这在它们的类型中并不明显。因此,当 typescript 计算 if (!b && !!a) { 时,它只知道两个变量都是 number | undefined。如果这就是您所知道的,那么在第二个 if 之后,ab 仍然可能未定义。

    我的 if 语句比您预期的更复杂(即我有 !a && !!b 而不仅仅是 !a),因为如果其他参数不存在,我想使用现有参数。

    如果您不需要使用现有参数,我建议您只删除 !!b!!a。但既然你这样做了,我建议将你的代码重新排列为以下之一:

    function test(a: number | undefined, b: number | undefined) {
      if (!a || !b) {
        if (a) {
          console.log('b is not present, we only found a - do a thing with a');
          return;
        }
        if (b) {
          console.log('a is not present, we only found b - do a thing with b');
          return;
        }
        console.log('Neither are present');
        return;
      }
    
      console.log(a + b);
    }
    

    或者:

    function test(a: number | undefined, b: number | undefined) {
      if (!a) {
        if (!b) {
          console.log('Neither are present');
          return;  
        }
    
        console.log('a is not present, we only found b - do a thing with b');
        return;
      }
      if (!b) {
        console.log('b is not present, we only found a - do a thing with a');
        return;
      }
      
      console.log(a + b);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多