代码之家  ›  专栏  ›  技术社区  ›  ironic

TypeScript如何推断数组文本的元素类型?

  •  2
  • ironic  · 技术社区  · 7 年前

    特别是,为什么要编译此代码(使用--noImplicitAny)

    function x() {
        const c = [];
        c.push({});
        c.indexOf({});
        return c;
    }
    

    然而,这并不是:

    function x() {
        const c = [];
        c.indexOf({});
        c.push({});
        return c;
    }
    

    enter image description here

    1 回复  |  直到 7 年前
        1
  •  6
  •   Titian Cernicova-Dragomir    7 年前

    这是预期的行为看到这个GitHub issue . 这里描述的函数与您的函数类似,问题是为什么没有出现错误 noImplicitAny 已打开:

    function foo() {
      const x = []
      x.push(3)
      return x
    }
    

    数组的类型被推断为“进化数组”类型。然后就变成了 number 第一次之后 x.push . 福应该回来了 number [] 如果 x 在控制流确定其类型之前见证,并产生错误。例如。:

    function foo() {
      const x = []
      x.push(3)
      return x;
    
      function f() { 
        x; // error, x is `any`.
      }
    }
    

    对你来说, indexOf 索引 push

    推荐文章