Skip to content

[Bug]: property access on negative number isn't preserved as negative number in the output #15801

@Andarist

Description

@Andarist

💻

  • Would you like to work on a fix?

How are you using Babel?

Programmatic API (babel.transform, babel.parse)

Input code

const result = require("@babel/core").transformSync(
  `
  export default 'hello';
`,
  {
    plugins: [
      function (babel) {
        const { types: t } = babel;

        return {
          visitor: {
            StringLiteral(path) {
              path.replaceWith(
                t.unaryExpression(
                  "typeof",
                  t.callExpression(
                    t.memberExpression(
                      t.numericLiteral(-1),
                      t.identifier("toString")
                    ),
                    []
                  )
                )
              );
            },
          },
        };
      },
    ],
  }
);

console.log(result.code);

Configuration file name

No response

Configuration

none

Current and expected behavior

current

export default typeof -1 .toString(); // evaluated as 'number'

expected

export default typeof (-1).toString(); // evaluated as 'string'

Environment

System:
OS: macOS 12.3
Binaries:
Node: 20.2.0 - ~/Library/Caches/fnm_multishells/2251_1687933194251/bin/node
Yarn: 1.22.17 - /usr/local/bin/yarn
npm: 9.6.6 - ~/Library/Caches/fnm_multishells/2251_1687933194251/bin/npm
pnpm: 7.27.1 - ~/Library/pnpm/pnpm
npmPackages:
@babel/core: ^7.22.9 => 7.22.9

Possible solution

wrap negative numbers in member expressions with parentheses

Additional context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    i: needs triageoutdatedA closed issue/PR that is archived due to age. Recommended to make a new issue

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions