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.