TypeScript: Regression: Not-null assertion causes implicit any

TypeScript Version: 2.7.0-dev.20171029

Code

function test(numbers: number[]) {
    let last;

    for (const n of numbers) {
        if (n % 2) {
            return n;
        }

        last = n;
    }

    return last!; // without the bang, last is inferred as `number | null`
                  // adding the bang causes implicit any
}

Workaround: Initialise the “tracking” variable with undefined.

function test(numbers: number[]) {
    let last = undefined;

    for (const n of numbers) {
        if (n % 2) {
            return n;
        }

        last = n;
    }

    return last!; // OK
}

Expected behavior: Should compile successfully with and without a bang.

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Comments: 24 (12 by maintainers)

Commits related to this issue

Most upvoted comments

@aminpaks I still see the error in the Typescript playground with the 4.1.3 (current latest version). Your code snippet is missing the non-null assertion (return last; instead of return last!;).

Is anyone still on it? Can I give it a shot as a first issue?

Yup - I mostly just wanted to check if you were using a different package manager.

I meant how did you install the prerequisites in our package.json. 😄