Skip to content

[Bug]: TypeScript type only import namespace aliases are not removed #15942

@youngderekm

Description

@youngderekm

💻

  • Would you like to work on a fix?

How are you using Babel?

@babel/cli

Input code

import { X } from "abc";
// assume Y is a type only namespace
import Z = X.Y.Z;

function a(t: Z.T) {
  console.log(t);
}

Configuration file name

babel.config.js

Configuration

export = {
  assumptions: {
  },
  presets: [
    ["@babel/preset-env", {
      // preserve ES module syntax (imports, exports)
      modules: false,
      targets: {
        firefox: "91",
        chrome: "88",
        edge: "88"
      }
    }],
    ["@babel/preset-typescript", {
      allowNamespaces: true,
      allowDeclareFields: true
    }],
    "@babel/preset-react"
  ],
  plugins: [
    ["@babel/plugin-transform-typescript", {
      allowDeclareFields: true,
    }],
    ["@babel/plugin-proposal-decorators", {
      "legacy": true
    }],
    ["@babel/plugin-transform-class-properties", {"loose": false}],
    "@babel/plugin-proposal-private-property-in-object",
    "@babel/plugin-transform-runtime",
  ],
}

Current and expected behavior

As with TypeScript, no code is now generated for type only namespaces. However, if you import a type only namespace using an import alias, code is generated for this import, which can crash at runtime. In the example input code, Z is a type only namespace with an interface T inside of if (or any other type). Since it's only used as a type in the code, the code for the alias should be removed. Instead, the generated code includes

var Z = X.Y.Z;

Because Y doesn't exist (it's type only), X.Y.Z crashes (Y is undefined).

I would expect no code to be generated for import Z = X.Y.Z.

Environment

    "@babel/core": "7.22.15",
    "@babel/plugin-transform-class-properties": "7.22.5",
    "@babel/plugin-proposal-decorators": "7.22.15",
    "@babel/plugin-proposal-private-property-in-object": "7.21.11",
    "@babel/plugin-transform-runtime": "7.22.15",
    "@babel/plugin-transform-typescript": "7.22.15",
    "@babel/preset-env": "7.22.15",
    "@babel/preset-react": "7.22.15",
    "@babel/preset-typescript": "7.22.15",

node 16.16.0

Possible solution

No response

Additional context

Repl example demonstrating

Metadata

Metadata

Assignees

Labels

area: typescripti: regressionoutdatedA closed issue/PR that is archived due to age. Recommended to make a new issue

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions