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.
returnstatement has an implicit semicolon so ifget(type)returns a falsy value it won't then trythis.add(type, new type()). Also, usePascalCasefor classes, notcamelCase.node -vto find out.??operator is supported by NodeJS 14.0 or later. It is also supported by NodeJS 13 if you use the--harmony-nullishflag (you also might want to enable--harmony-optional-chainingtoo). If you're using an older version of Node then you probably should update.