2

为什么 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));
                }      
            }      
    }

日志消息.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 无法再解决。如果我使用不同的模块名称定义 GridUtils,例如 jqGridUtilities 而不是 Utilities,我将不再收到此错误。为什么是这样?

4

1 回答 1

2

这是我根据你的例子得到的......

看起来您正在采用捆绑策略...即您要求 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));
        }
    }
}
于 2012-10-29T21:41:09.920 回答