I am making server side chat with colyseus (node game server framework). Im using typescript with module:commonjs because colyseus is built upon commonjs.
I have class ChatRoom
that extends Colyseus.Room
.
At run-time I get this error:
Class constructor Room cannot be invoked without 'new'.
And the trouble in javascript:
function ChatRoom() {
return _super !== null && _super.apply(this, arguments) || this;
}
from typescript class:
import {Room} from "colyseus";
export class ChatRoom extends Room {
onInit(options) {
console.log("BasicRoom created!", options);
}
onJoin(client) {
this.broadcast(`${ client.sessionId } joined.`);
}
onLeave(client) {
this.broadcast(`${ client.sessionId } left.`);
}
onMessage(client, data) {
console.log("BasicRoom received message from", client.sessionId, ":", data);
this.broadcast(`(${ client.sessionId }) ${ data.message }`);
}
onDispose() {
console.log("Dispose BasicRoom");
}
}
The error is easily skipped when troubled row is removed after compilation. But the base class is not created and this is not a complete solution.
I googled the issue and it seems to relate to babel transpiler, though I don't use babel. I only use tsc / tsconfig.json.
TypeScript transpiles a class to its ES5 counterpart, but this way it's necessary that entire class hierarchy is transpiled to ES5.
In case parent class is untranspiled (native class or imported ES6 class, including the ones that were transpiled with Babel), this won't work, because TypeScript relies on var instance = Parent.call(this, ...) || this
trick to call parent constructor, while ES6 classes should be called only with new
.
This problem should be solved in Node.js by setting TypeScript target
option to es6
or higher. Modern Node.js versions support ES6 classes, there is no need to transpile them.
The same problem applies to Babel.