TypeScript 导入模块在当前范围内不存在

标签 typescript

为什么 TypeScript 编译器会在 Logger.ts 中发出错误“名称 m 在当前范围内不存在”,即使它能够解析 Model.LogMessage 定义的 LogMessage.ts

这些是关联文件:

记录器.ts:

    ///<reference path="Utils.ts"/>
    /// <reference path="../Models/LogMessage.ts"/>
    /// <reference path="JqGridUtilities.ts"/>



    module Utilities {

        declare var $;
        import m = Model;
        //import jqu = Utilities;

        export class Logger {        

                static logs:  m.LogMessage[];  // how to do typed array????

                logs1: m.LogMessage[];

                static logsGridClass = "jqgdash_logs";
                static gridName = "jqgdash";
                static logsGridHeader = "Info Center";            

  static displayDataOnConsole(gridClass : string, gridHeader : string, theData) {

                if (theData != null && theData.length > 0) {
                    var grid = $("#" + gridName);

                    if (gridClass === logsGridClass) {
                        if (!grid.hasClass(logsGridClass)) {
                            GridUtils.reconfigureGrid(gridName, gridHeader, theData);
                            grid.addClass(logsGridClass);
                        } else {
                            GridUtils.addDataToGrid(gridName, gridHeader, theData);
                        }   
                    } else {
                        if (grid.hasClass(logsGridClass)) {
                            grid.removeClass(logsGridClass);
                    }

                    GridUtils.reconfigureGrid(this.gridName, gridHeader, theData);
                }
            }
        }


          static  createErrorLogs(messages : string) : m.LogMessage[] {
                    if (messages == null) return [];
                    $.each(messages, function (i, msg) {
                        logs.push(this.createLogJson("error", msg));
                    });

                    return logs;
                }

           static logMessageToConsole (severity : string, message : string) {
                    this.logs.push(this.createLogJson(severity, message));
                }      
            }      
    }

LogMessage.ts:

module Model { 
       export class LogMessage {

        message: string;
        timeStamp: Date; 
        severity: string;

        constructor (severity : string, message: string, date: Date) {
            this.message = message;
            this.timeStamp = date;
            this.severity = severity;
        }
     }
}

和Utils.ts:

module Utils { 

    declare var tut;

   export var liveString = "http://" + window.location.host + '/trackutransit';

    export function executeAjaxPostJsonCall(url : string, success : any ) { 
        return  $.ajax(url,
        {
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            error: tut.Logger.displayAjaxError,
            success : success  });
         }

   export function getResourcePath(relativePath: string): string {
            return liveString + relativePath;
        }

    export function isMobile(): bool {
            var index = navigator.appVersion.indexOf("Mobile");
            return (index > -1);
        }
}

JQGridUtilities.ts 与 Logger.ts 定义在同一文件夹中,如下所示:

///<reference path="Utils.ts"/>
module Utilities{

    declare var jqGrid;


    declare var $;
    //import t = TrackuTransit;

    export class GridUtils {

        static instance = new GridUtils();

        constructor() { }

      static  isUserFriendlyField(key : string) : bool {    
        return true;
    }

    // Extracts the fields from this Json object
   static extractColumnsFromJsonObject(obj) : any[]{
        var columns = new Array();
        if (obj) {
            for (var key in obj) {
                if (isUserFriendlyField(key)) {
                    columns.push(key);
                }
            }
        }

        return columns;
    }

   static  addDataToGrid(gridId, gridHeader, data) {
        if (data != null) {
            var grid = $("#" + gridId);
            for (var i = 0; i < data.length; i++) {
                grid.jqGrid('addRowData', i, data[i]);
            }
        }
    }

    static createColumnModels(columns)  : any[]{

        var model = [];

        $.each(columns, function (i, column) {
            if (this.isUserFriendlyField(column)) {
                if (column === "icon" || column === "image") {
                    model.splice(0, 0, { name: column, label: ' ', width: 16, formatter: function (cellvalue, options, rowObjects) {
                        return "<img src='" + cellvalue + "' width='16px' height='16px'/>";
                    }
                    });
                }
                else if (column === "Severity") {
                    model.splice(0, 0, {
                        name: column,
                        label: ' ',
                        width: 20,
                        formatter: function (cellvalue, options, rowObjects) {
                            var imagePath = Utils.liveString + '/Content/images/' + cellvalue + '.png';
                            return "<img src='" + imagePath + "' width='16px' height='16px'/>";
                        }
                    });
                }
                else {
                    if (column === "display_name") {
                        model.splice(0, 0, { name: column, label: "name" });
                    } else {
                        model.push({ name: column, label: column, width: 70 });
                    }
                }
            }
        });

        return model;
    }

   static reconfigureGrid(gridName, gridHeader, theData) {
        if (!gridName)
            throw ("grid name must be specified");

        if (gridHeader, theData != null && gridHeader, theData.length > 0) {

            var columns = extractColumnsFromJsonObject(theData[0]);
            var colsModel = createColumnModels(columns);

            // todo: report unable to chain jQuery methods as bug for jqGrid
            $("#" + gridName).jqGrid('GridUnload');
            $("#" + gridName).jqGrid({
                datatype: "local",
                data: theData,
                autowidth: true,
                colModel: colsModel,
                pager: '#pager',
                rowNum: 10,
                rowList: [5, 10, 20, 50],
                height: 120,   // constant height allows grid navigator to show, if parent div is constant height
                width: '100%',
                viewrecords: true,
                caption: gridHeader
            });
        }
    }


    }

}

如果我在 Logger.ts 中删除对 JqGridUtilities.ts 的引用,错误就会消失,但现在无法再解析 GridUtils。如果我使用不同的模块名称(例如 jqGridUtilities 而不是 Utilities)定义 GridUtils,我将不再收到此错误。这是为什么?

最佳答案

这是我根据您的示例得出的结果...

看起来您正在采取捆绑策略...即您要求 TypeScript 保留 JavaScript 的加载方式。您可以将所有脚本添加到页面,也可以将它们捆绑到一个文件中并缩小它。

执行此操作时,您几乎可以忽略 import 关键字,而仅使用 reference 注释来描述您将在运行时提供的文件。

考虑到这一点,这是您的 Logger.ts 文件

这些变化主要是缺少 import 语句,但我还展示了如何实例化类型化数组(只需在声明后加上 = [] 即可。

/// <reference path="Utils.ts"/>
/// <reference path="./Models/LogMessage.ts"/>
/// <reference path="JqGridUtilities.ts"/>

module Utilities {
    declare var $;

    export class Logger {

        static logs: Model.LogMessage[] = [];  // how to do typed array? - Like this

        logs1: Model.LogMessage[] = [];

        static logsGridClass = "jqgdash_logs";
        static gridName = "jqgdash";
        static logsGridHeader = "Info Center";

        static displayDataOnConsole(gridClass: string, gridHeader: string, theData) {

            if (theData != null && theData.length > 0) {
                var grid = $("#" + gridName);

                if (gridClass === logsGridClass) {
                    if (!grid.hasClass(logsGridClass)) {
                        GridUtils.reconfigureGrid(gridName, gridHeader, theData);
                        grid.addClass(logsGridClass);
                    } else {
                        GridUtils.addDataToGrid(gridName, gridHeader, theData);
                    }
                } else {
                    if (grid.hasClass(logsGridClass)) {
                        grid.removeClass(logsGridClass);
                    }

                    GridUtils.reconfigureGrid(this.gridName, gridHeader, theData);
                }
            }
        }


        static createErrorLogs(messages: string): m.LogMessage[] {
            if (messages == null) return [];
            $.each(messages, function (i, msg) {
                logs.push(this.createLogJson("error", msg));
            });

            return logs;
        }

        static logMessageToConsole(severity: string, message: string) {
            this.logs.push(this.createLogJson(severity, message));
        }
    }
}

关于TypeScript 导入模块在当前范围内不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13124693/

相关文章:

javascript - Typescript:通用不可变集合

html - Angular 4 Ngx-translate 管道不工作

javascript - Angular 2\TypeScript 中 export 关键字的确切含义是什么?

node.js - Visual Studio 找不到 Firebase Node 模块

javascript - 以对象为键的 Typescript Map

typescript Jest 全局变量示例

javascript - 扁平化同步 Angular promise

typescript - 在 Typescript 中,为数组定义一个类型,其中第一个元素比其余元素更具体

html - OnChange typescript 输入

typescript - Intellij 找不到 tsconfig.json