This is the expected behavior see this GitHub issue. The function described there is similar to yours, the question being why no error is raised with noImplicitAny turned on:
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`.
}
}
So in your case, indexOf witnesses the type of the array before a type can be determined and an error is raised. If indexOf is called after push the type is determined and no error is raised.
Sharebutton to get a URL to the TypeScript playground with this code in it. That way we can all reproduce it easily.pushhelps determine the type of element that is in the array;indexOfdoesn't.const c: object[] = []