【问题标题】:SyntaxError: Unexpected Token '?' discord.jsSyntaxError: Unexpected Token '?'不和谐.js
【发布时间】:2021-11-02 05:07:44
【问题描述】:

我正在使用 discord.js 版本 12.5.3,我也在为我的项目使用 repli。我不断收到此错误:

这是我的代码:

export default class Deps {
  static #instances = new Map();

  static get(type) {
    return this.#instances.get(type)
      ?? this.add(type, new type());
  }

  static add(type, instance) {
    return this.#instances
      .set(type, instance)
      .get(type);
  }
}

【问题讨论】:

  • return 语句有一个隐含的分号,所以如果get(type) 返回一个假值,它不会然后尝试this.add(type, new type())。此外,使用PascalCase 进行课程,而不是camelCase
  • 我仍然遇到同样的错误。
  • 你运行的是什么版本的 NodeJS?运行node -v 找出答案。
  • 根据kangax.github.io/compat-table/es2016plus?? 运算符由 NodeJS 14.0 或更高版本支持。如果您使用 --harmony-nullish 标志,NodeJS 13 也支持它(您也可能希望启用 --harmony-optional-chaining)。如果您使用的是旧版本的 Node,那么您可能应该更新。
  • 我使用的是 12.16.1 版本,但我无法更新它,因为没有下载功能。有没有办法通过 shell 或控制台来做到这一点? (非常感谢您到目前为止的帮助)

标签: node.js discord.js


【解决方案1】:

简答?? 需要与 return 语句位于同一行:

export default class Deps {
  static #instances = new Map();

  static get(type) {
    return this.#instances.get(type) ?? this.add(type, new Type()); // <-- Like this
  }

  static add(type, instance) {
    return this.#instances
      .set(type, instance)
      .get(type);
  }
}

更长的答案The return statement in JavaScript has special automatic semicolon insertion ("ASI") rules 这意味着您需要将整个表达式放在一行中,或者使用括号使您的return 语句的表达式清晰地跨越多行。

所以你可以也这样做:

export default class Deps {
  static #instances = new Map();

  static get(type) {
    return ( this.#instances.get(type)    // <-- Opening `(` here.
        ?? this.add(type, new Type())
    );                                    // <-- Closing `)` here.
  }

  static add(type, instance) {
    return this.#instances
      .set(type, instance)
      .get(type);
  }
}

在我开始使用 TypeScript 之前,我一直被return ASI 规则刺痛,却没有意识到:这是一个常见的错误来源。

【讨论】:

    猜你喜欢
    • 2020-12-09
    • 1970-01-01
    • 1970-01-01
    • 2020-11-02
    • 2017-06-10
    • 1970-01-01
    • 2012-05-17
    • 2019-02-10
    • 2019-11-10
    相关资源
    最近更新 更多