0

I'm using discord.js version 12.5.3, I also am using replit for my project. I keep getting this error: enter image description here

This is my code:

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);
  }
}
Jay
  • 51
  • 1
  • 1
  • 6
  • The `return` statement has an implicit semicolon so if `get(type)` returns a falsy value it _won't_ then try `this.add(type, new type())`. Also, use `PascalCase` for classes, not `camelCase`. – Dai Sep 04 '21 at 02:39
  • i'm still getting the same error. – Jay Sep 04 '21 at 08:55
  • What version of NodeJS are you running? Run `node -v` to find out. – Dai Sep 04 '21 at 09:17
  • According to https://kangax.github.io/compat-table/es2016plus/ the `??` operator is supported by NodeJS 14.0 or later. It is also supported by NodeJS 13 if you use the `--harmony-nullish` flag (you also might want to enable `--harmony-optional-chaining` too). If you're using an older version of Node then you probably should update. – Dai Sep 04 '21 at 09:26
  • I'm on version 12.16.1 but i can't update it because there is no download feature. Is there any way to do this through the shell or console? (Thanks so much for your help so far) – Jay Sep 05 '21 at 09:21
  • I updated it thank you so much Dai, I really appreciate your help. – Jay Sep 05 '21 at 23:10

1 Answers1

1

Short answer: The ?? needs to be on the same line as the return statement:

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);
  }
}

Longer answer: The return statement in JavaScript has special automatic semicolon insertion ("ASI") rules which mean you need to have the entire expression on a single line, or use parentheses so that your return statement's expression clearly spans multiple lines.

So you could also do this:

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);
  }
}

Before I started using TypeScript I used to get stung by return ASI rules all the time without realising it: it's a frequent source of bugs.

Dai
  • 141,631
  • 28
  • 261
  • 374