TypeScript定义外部类

TypeScript define external class

本文关键字:外部 定义 TypeScript      更新时间:2023-09-26

当前我的代码如下:

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。)

确保您的模块如下所示:

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;

然后,与其使用/// <reference />,不如这样做:

import Nexus = require('Nexus');

您还需要导出模块

export module Nexus {
    ...
}

然后在你的应用程序中,你可以这样称呼它:

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