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?

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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 :-)
I'm glad the answer helped.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.