Skip to content

Aggressive "used before assigned" with strictNullChecks #9757

Closed
@kitsonk

Description

@kitsonk

TypeScript Version: 2.0.0 (beta)

Code

// @strictNullChecks: true

function on(event: string, callback: () => void): { destroy(): void; } {
    return {
        destroy() {
            /* nothing */
        }
    };
}

const handle = on('example', () => {
    handle.destroy(); // error TS2454: Variable 'handle' is used before being assigned.
});

Expected behavior:

Compile without errors.

Actual behavior:

Error that handle is being used before it is assigned.

It seems to be overly aggressive behaviour which means using block scoped variables in a callback is causing usability issues. Shouldn't flow control assumed that functions would be resolved after the function returns a value?

Seems to be a little bit related to #9382, but in this case, the type is resolvable (and handle.destroy() provides insight. I also noticed that in VSCode, while other compiler errors are displaying, this one isn't getting flagged in the IDE (that may still just be my setup though).

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugA bug in TypeScriptFixedA PR has been merged for this issue

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions