node.jstypescripttypescript1.6

How to properly extend a class with TypeScript in NodeJS?


I want to use TypeScript in a NodeJS environment. Since I'm absolutely new to TypeScript I'm not sure how to extend classes properly with the NodeJS module system.


I want to extend my class Champion with GameObject.

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;

This throws no compilation error so far.

Now I want to create an instance of my Champion. This is what I've tried

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

My Champion.js now throws the following error:

ReferenceError: GameObject is not defined

So I thought I need to require('GameObject') in Champion.ts which make my application running. But I get another error.

Either I reference and require my GameObject

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

Which gives me the error

Duplicate Identifier GameObject

Or I just require and get

Type any is not a constructor function type

TypeScript Version

$ tsc -v
message TS6029: Version 1.6.2

Solution

  • Instead of using module.exports = GameObject; with var/require use import/require

    This will give you type safety on the import side. These are called file modules and documented here : https://basarat.gitbooks.io/typescript/content/docs/project/modules.html