网站搜索

typescript - OptionalMemberExpression 的 property 属性预期节点类型为 ["Identifier"],但实际得到的是 "CallExpression"


我有一行代码,看起来像这样:

return someObj.getSomething(param).doSomethingElse().key.anotherKey

我所有的 Jest 单元测试都通过了。

为了更加安全一点,我在那一行添加了可选链,现在它看起来像这样:

return someObj?.getSomething(param)?.doSomethingElse()?.key?.anotherKey

一旦我那样做,相应的测试套件就会出现错误:

Test suite failed to run

    TypeError: Property property of OptionalMemberExpression expected node to be of a type ["Identifier"] but instead got "CallExpression"

      at validate (node_modules/@babel/types/lib/definitions/utils.js:132:11)
      at Object.validator [as validate] (node_modules/@babel/types/lib/definitions/core.js:1451:11)
      at validateField (node_modules/@babel/types/lib/validators/validate.js:24:9)
      at Object.validate (node_modules/@babel/types/lib/validators/validate.js:17:3)
      at NodePath._replaceWith (node_modules/@babel/traverse/lib/path/replacement.js:179:7)
      at NodePath.replaceWith (node_modules/@babel/traverse/lib/path/replacement.js:161:8)
      at RewireState.Identifier (node_modules/babel-plugin-rewire/lib/babel-plugin-rewire.js:187:10)
      at NodePath._call (node_modules/@babel/traverse/lib/path/context.js:55:20)
      at NodePath.call (node_modules/@babel/traverse/lib/path/context.js:42:17)
      at NodePath.visit (node_modules/@babel/traverse/lib/path/context.js:92:31)

可选链插件已被添加到我的 package.json 文件中,如下所示:

"dependencies" : {
    "@babel/plugin-proposal-optional-chaining": 7.14.5
}

以及在我的 babel.config.js 文件中。

任何帮助都将不胜感激。

答案#1

在我的情况下,这是因为将 hash 作为变量使用导致的。更改之后

let hash;

到

let hashStr;

问题已经解决。我正在使用 babel-plugin-rewire。