Skip to content

Regression: Not-null assertion causes implicit any #19577

Closed
@gcnew

Description

@gcnew

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugA bug in TypeScriptGood First IssueWell scoped, documented and has the green lightHelp WantedYou can do this

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions