Skip to content

.cts files are should not share the same top-level scope #49207

@nicolo-ribaudo

Description

@nicolo-ribaudo

Bug Report

NOTE: There are already multiple (open or closed) issues about this topic. However, this issue is specifically about the behavior in .cts files and not in .ts files.

.ts files disallow using top-level block-scoped variables with the same name because they would conflict when loaded with a <script> tag.

.cts files currently have the same restriction, however:

  • This extension is explicitly documented as referring to CommonJS files. CommonJS doesn't share a single top-level scope, because every file is wrapped in a function. This means that top-level variables with the same name will not conflict.
  • When using CommonJS files, it's common to use the same variable name when importing the same dependency in multiple files. This error makes it impossible to do so.

For these reasons, I think that this restriction should be removed.

A real word example: I'm updating typescript to 4.7 in the Babel repository, and I hoped to be able to convert our remaining JavaScript files to TypeScript. They are still JS because we needed to use the .cjs extension: https://github.com/babel/babel/tree/main/eslint/babel-eslint-parser/src. However, most of those files use the same variables names to import other files, so I'm unable to do so.

🔎 Search Terms

cts top-level Cannot redeclare block-scoped variable

🕗 Version & Regression Information

  • Tested in TS4.7, where .cts has been introduced

⏯ Playground Link

n/a (it requires multiple files)

💻 Code

file1.cts:

const { getVisitorKeys } = require("./ast-info.cjs");

file2.cts:

const { getVisitorKeys } = require("./ast-info.cjs");

🙁 Actual behavior

eslint/babel-eslint-parser/src/worker/maybeParse.cts:3:25 - error TS2451: Cannot redeclare block-scoped variable 'getVisitorKeys'.

3 const { getVisitorKeys } = require("./ast-info.cjs");
          ~~~~~~~~~~~~

  eslint/babel-eslint-parser/src/worker/handle-message.cts:3:25
    3 const { getVisitorKeys } = require("./ast-info.cjs");
              ~~~~~~~~~~~~
    'getTokLabels' was also declared here.

🙂 Expected behavior

No error

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptFix AvailableA PR has been opened for this issue

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions