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

How does TypeScript infer element type for array literals?

特别是为什么这段代码可以编译(使用 --noImplicitAny)

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

然而,这不是:

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

这是预期的行为,请参阅此 GitHub issue。那里描述的功能与您的相似,问题是为什么 noImplicitAny 打开时不会引发错误:

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

The type of the array is inferred to be an "evolving array" type. it then becomes number after the first x.push. foo should be returning number []. If the type of x is witnessed before control flow can determine its type, and error is produced. e.g.:

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

  function f() { 
    x; // error, x is `any`.
  }
}

因此,在您的情况下,indexOf 在确定类型并引发错误之前见证数组的类型。如果在 push 之后调用 indexOf,则确定类型并且不会引发错误。