TypeScript定义外部类

时间:2015-03-26 15:23:12

标签: javascript node.js typescript

目前我的代码如下:

module Nexus {

    export class Scrapper {

        private summonerName: string;

        private apiKey: string = '';

        private summonerStatsUrl = '';

        constructor(name: string) {

            this.summonerName = name;
        }

        getSeasonRank(): string {

            return 'aa';
        }

        getRankedStats(): string {

            return 'aa';
        }

        getSummonerStats(callback: Function) {

            var summonerStats = request(this.summonerStatsUrl + this.apiKey, function (error, body, response) {

                callback(response);
            });
        }
    }
}

app.ts

///<reference path="./Nexus.ts"/>

var colors = require('colors'),
    request = require('request'),
    fs = require('fs'),
    readline = require('readline'),
    rl = readline.createInterface({

        input: process.stdin,
        output: process.stdout
    });

rl.question('Insert summoner name: \r\n >> ', function (answer) {

    var scrapper = new Nexus.Scrapper(answer);

    scrapper.getSummonerStats(function (result) {

        console.log(result);
    });
});

当我到达新Nexus.Scrapper()时,我收到此错误:

未定义Nexus

虽然它应该是因为我包括它?该模块名为 Nexus ,我正在导出Scrapper类。 (该文件名为 Nexus.ts 。)

2 个答案:

答案 0 :(得分:2)

确保您的模块如下所示:

module Nexus {
    export class Scrapper {
        private summonerName: string;
        private apiKey: string = '';
        private summonerStatsUrl = '';

        constructor(name: string) {

            this.summonerName = name;
        }

        getSeasonRank(): string {

            return 'aa';
        }

        getRankedStats(): string {
            return 'aa';
        }

        getSummonerStats(callback: Function) {
            var summonerStats = request(this.summonerStatsUrl + this.apiKey, function (error, body, response) {
                callback(response);
            });
        }
    }
}

export = Nexus;

然后,而不是使用/// <reference />执行此操作:

import Nexus = require('Nexus');

答案 1 :(得分:1)

您还需要导出模块

export module Nexus {
    ...
}

然后在您的app.ts中,您可以将其称为:

import Nexus = require('./Nexus.ts');