Skip to content

const/let variables with require() initializer are not correctly block-scoped #41697

Closed
@sokra

Description

@sokra

TypeScript Version: 4.2.0-dev.20201126

Search Terms: TS2300

Code

// compiled in JS mode. Works fine when compiled as TS
switch(something) {
    case "a": {
        const x = require("fs"); // TS2300: Duplicate identifier 'x'
        console.log(x);
        break;
    }
    case "b": {
        const x = require("fs"); // TS2300: Duplicate identifier 'x'
        console.log(x);
        break;
    }
    case "c": {
        const x = 123; // No error (only happens with require() as initializer)
        console.log(x);
        break;
    }
}
x.readFileSync("x"); // should be error

Expected behavior:

No TS2300 error. const variables should be block-scoped.

Actual behavior:

const variables with require() initializer leak into outer scope. Looks like they are incorrectly function scoped.

Playground Link: Playground link

Related Issues:

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptDesign LimitationConstraints of the existing architecture prevent this from being fixed

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions