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);
  }
}
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. Commented Sep 4, 2021 at 2:39
  • i'm still getting the same error. Commented Sep 4, 2021 at 8:55
  • What version of NodeJS are you running? Run node -v to find out. Commented Sep 4, 2021 at 9:17
  • According to 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. Commented Sep 4, 2021 at 9: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) Commented Sep 5, 2021 at 9:21

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.