【问题标题】:TypeScript define external classTypeScript 定义外部类
【发布时间】:2015-03-26 15:23:11
【问题描述】:

目前我的代码如下所示:

module Nexus {

    export class Scraper {

        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 scraper = new Nexus.Scraper(answer);

    scraper.getSummonerStats(function (result) {

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

当我到达新的Nexus.Scraper() 时,我收到了这个错误:

Nexus 未定义

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

【问题讨论】:

  • 建议模块名以小写字母开头。什么是 "///" ? Nexus 是一门课吗?打字稿文件的名称应与类的名称相同。你的 app.ts 应该在同一个模块中,即 nexus。然后它会工作

标签: javascript node.js typescript


【解决方案1】:

确保您的模块如下所示:

module Nexus {
    export class Scraper {
        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;

然后,不要使用/// &lt;reference /&gt;,而是这样做:

import Nexus = require('Nexus');

【讨论】:

    【解决方案2】:

    你还需要导出模块

    export module Nexus {
        ...
    }
    

    然后在你的 app.ts 中你可以这样称呼它:

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

    【讨论】:

    • '在 app.ts 上找不到名称 Nexus'
    • 如果我没记错的话,你还需要在 app.ts 上要求它。
    猜你喜欢
    • 1970-01-01
    • 2014-11-06
    • 1970-01-01
    • 2014-11-12
    • 2015-01-30
    • 2021-03-15
    • 1970-01-01
    • 2023-03-03
    • 2015-08-07
    相关资源
    最近更新 更多