2

I'm seriously considering switching to Node.js from PHP. But I don't really like the prototyping in Javascript so I would favor Typescript over this.

I was just testing the basics and created a new (Typescript) Express project in Visual Studio 2013. I have Node.js for Visual Studio installed.

I created a directory called tstests, added a file called animals.ts with the following code from the Typescript tutorial:

class Animal {
    name: string;
    constructor(theName: string) { this.name = theName; }
    move(meters: number) {
        alert(this.name + " moved " + meters + "m.");
    }
}

class Snake extends Animal {
    constructor(name: string) { super(name); }
    move() {
        alert("Slithering...");
        super.move(5);
    }
}

class Horse extends Animal {
    constructor(name: string) { super(name); }
    move() {
        alert("Galloping...");
        super.move(45);
    }
}

Then I added the following piece of code to app.ts:

/// <reference path='tstests/animals.ts'/>
var sam = new Snake("Sammy the Python");
sam.move();

Both IntelliSense and building the project work, but when I try to run the project I get a ReferenceError: Snake is not defined.

Can anyone explain to me how I have to solve this?

jessehouwing
  • 106,458
  • 22
  • 256
  • 341

1 Answers1

3

As you are running on Node, you can use external modules.

Replace:

/// <reference path='tstests/animals.ts'/>

With

import Animals = require('tstests/animals');

And in animals.ts add the word export to any class you want to make available...

//...
export class Snake extends Animal {
//...

You can now reference the Snake class using:

var sam = new Animals.Snake("Sammy the Python");

Node will load the modules for you and make them available.

If you were running in a browser, you would have to make sure you referenced each script in the right order within a script tag - but you can avoid all that work as Node will do it all for you.

Fenton
  • 241,084
  • 71
  • 387
  • 401
  • That did the trick, thanks! I have to say, every article I found on the internet just confused me more as some talked about AMD, others CommonJS, RequireJS, ... And none of them had a really clear example on using multiple files. And in the end after reading up on TypeScript modules I got even more dazed :-) – Kristof Torfs Jul 17 '14 at 17:20
  • I'm glad the answer helped. – Fenton Jul 18 '14 at 09:40