Skip to content

TDZ error is a bit overzealous #3656

Closed
Closed
@Arnavion

Description

@Arnavion
function foo() {
    function bar() {
        x = 5;
    }
    let x;
    bar();
    console.log(x);
}

This complains that x = 5; is referencing x before its declaration. While technically true, this is not really a TDZ error. Though the access of x appears before its declaration in source code order, it's being executed after it, so the assignment will not throw a ReferenceError and is valid ES6 that will log 5

If it was bar(); let x; instead, then the error would be valid, since then the assignment would be invoked in x's TDZ.

But detecting this statically will require some brittle / expensive flow analysis, and it's not hard to reorder the code so it doesn't hit this, so maybe it's okay to leave it unfixed. The only real life scenario I can think of that would hit this problem is an existing codebase that prefers to put functions at the top of their respective scopes, that then starts migrating from var to let and const.

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugA bug in TypeScriptDuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions