【问题标题】:How to properly extend a class with TypeScript in NodeJS?如何在 NodeJS 中使用 TypeScript 正确扩展类?
【发布时间】:2015-11-15 13:10:05
【问题描述】:

我想在 NodeJS 环境中使用 TypeScript。由于我对 TypeScript 完全陌生,我不确定如何使用 NodeJS 模块系统正确扩展类。


我想用GameObject 扩展我的课程Champion。

GameObject.ts

///<reference path="../../typings/node/node.d.ts"/>

class GameObject {
    id:number;
    name:string;
}

module.exports = GameObject; 

Champion.ts

///<reference path="../../typings/node/node.d.ts"/>
///<reference path="Image.ts"/>
///<reference path="GameObject.ts"/>


class Champion extends GameObject {
    // ...
}

module.exports = Champion;

到目前为止,这不会引发编译错误。

现在我想创建我的 Champion 的一个实例。这是我尝试过的

// I tried referencing the Champion.ts which haven't changed anything
var Champion = require('../api/types/Champion');
var c = new Champion();

我的Champion.js 现在抛出以下错误:

ReferenceError: GameObject 未定义

所以我想我需要在Champion.ts 中输入require('GameObject'),这会使我的应用程序运行。但我得到另一个错误。

我参考和require 我的GameObject

///<reference path="GameObject.ts"/>
var GameObject = require('./GameObject');
class Champion extends GameObject {

这给了我错误

重复的标识符游戏对象

或者我只是 require 并得到

type any 不是构造函数类型

TypeScript 版本

$ tsc -v
message TS6029: Version 1.6.2

【问题讨论】:

    标签: node.js typescript typescript1.6


    【解决方案1】:

    不要使用module.exports = GameObject; 和var/require 使用import/require

    这将为您在导入方面提供类型安全。这些被称为文件模块并记录在这里:https://basarat.gitbooks.io/typescript/content/docs/project/modules.html

    【讨论】:

      猜你喜欢
      • 2019-02-22
      • 2022-01-21
      • 2021-06-02
      • 1970-01-01
      • 2022-08-09
      • 2017-03-22
      • 2016-11-19
      • 2019-11-13
      • 2021-02-07
      相关资源
      最近更新 更多