没有'new'-不能调用类构造函数-commonjs的Typescript [英] Class constructor cannot be invoked without 'new' - typescript with commonjs

查看:248
本文介绍了没有'new'-不能调用类构造函数-commonjs的Typescript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在与colyseus(节点游戏服务器框架)进行服务器端聊天.我将typescript与module:commonjs一起使用,因为colyseus是基于commonjs构建的.

I am making server side chat with colyseus (node game server framework). Im using typescript with module:commonjs because colyseus is built upon commonjs.

我有扩展Colyseus.Room的类ChatRoom. 在运行时出现此错误:

I have class ChatRoom that extends Colyseus.Room. At run-time I get this error:

Class constructor Room cannot be invoked without 'new'.

以及javascript中的麻烦:

And the trouble in javascript:

function ChatRoom() {
   return _super !== null && _super.apply(this, arguments) || this;
}

来自打字稿类:

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.

我用谷歌搜索了这个问题,它似乎与babel transpiler有关,尽管我不使用babel.我只使用tsc/tsconfig.json.

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将类转换为与其ES5对应的类,但是这种方式需要将整个类层次结构转换为ES5.

TypeScript transpiles a class to its ES5 counterpart, but this way it's necessary that entire class hierarchy is transpiled to ES5.

如果父类是未编译的(本机类或导入的ES6类,包括使用Babel进行了编译的类),则此方法将不起作用,因为TypeScript依赖var instance = Parent.call(this, ...) || this技巧来调用父构造函数,而ES6类应只能用new调用.

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.

应该通过设置TypeScript target在Node.js中解决此问题选项es6.现代的Node.js版本支持ES6类,无需转换它们. 预设设置为节点目标.

This problem should be solved in Node.js by setting TypeScript target option to es6. Modern Node.js versions support ES6 classes, there is no need to transpile them. preset set to node target.

相同的问题适用于Babel .

这篇关于没有'new'-不能调用类构造函数-commonjs的Typescript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆