2

In particular, why this code compiles (with --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;
}

enter image description here

6
  • Both compiles with me, does it print out an error? Give us more information Commented Oct 14, 2018 at 16:46
  • @TareqEl-Masri, are you sure you enabled --noImplicitAny? Commented Oct 14, 2018 at 16:51
  • Please use the Share button to get a URL to the TypeScript playground with this code in it. That way we can all reproduce it easily. Commented Oct 14, 2018 at 16:55
  • 1
    push helps determine the type of element that is in the array; indexOf doesn't. Commented Oct 14, 2018 at 17:03
  • To determine the type of the array you can do it this way const c: object[] = [] Commented Oct 14, 2018 at 17:07

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Bonus question: is using only 'x.push(value), x.unshift(value) or x[n] = value' (and not indexOf(), etc) to evolve the array type somehow hardcoded into the compiler or it is defined somehow in one of d.ts files?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.