如何在 NodeJS 中使用 TypeScript 正确扩展 class?

How to properly extend a class with TypeScript in NodeJS?

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


我想用 GameObject.

扩展我的 class 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;

目前为止没有编译错误。

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

// 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 is not defined

所以我认为我需要在 Champion.tsrequire('GameObject'),这使我的应用程序 运行。但是我得到另一个错误。

要么我参考,要么 require 我的 GameObject

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

这给了我错误

Duplicate Identifier GameObject

或者我只是 require 然后得到

Type any is not a constructor function type

TypeScript 版本

$ tsc -v
message TS6029: Version 1.6.2

而不是使用 module.exports = GameObject;var/require 使用 import/require

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