[英]How does TypeScript infer element type for array literals?
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 firstx.push
.然后它变成
number
后的第一个x.push
。 foo should be returningnumber []
.foo应该返回
number []
。 If the type ofx
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.