简体   繁体   English

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

[英]How does TypeScript infer element type for array literals?

In particular, why this code compiles (with --noImplicitAny) 特别是为什么要编译此代码(使用--noImplicitAny)

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

while, this doesn't: 同时,这不会:

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

在此处输入图片说明

This is the expected behavior see this GitHub issue . 这是预期的行为,请参阅此GitHub 问题 The function described there is similar to yours, the question being why no error is raised with noImplicitAny turned on: 那里描述的功能与您的相似,问题是为什么打开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 . 然后它变成number后的第一个x.push foo should be returning number [] . foo应该返回number [] If the type of x is witnessed before control flow can determine its type, and error is produced. 如果在控制流可以确定x的类型之前就看到了x的类型,则会产生错误。 eg: 例如:

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

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

So in your case, indexOf witnesses the type of the array before a type can be determined and an error is raised. 因此,在您的情况下, indexOf在确定类型并引发错误之前会见证数组的类型。 If indexOf is called after push the type is determined and no error is raised. 如果在push后调用indexOf ,则确定类型,并且不会引发错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM