【问题标题】:TypeScript extend JQuery under NamespaceTypeScript 在命名空间下扩展 JQuery
【发布时间】:2016-01-21 12:36:05
【问题描述】:

我正在尝试通过 TypeScript 中的函数扩展默认的 JQuery 接口和默认对象 jQuery

代码

/// <reference path="jquery.d.ts" />

namespace MyNameSpace {
    var $ = jQuery;
    export interface JQuery {
        test(options: Object): JQuery;
    }
    $.fn.test = function(options: Object): JQuery {
        if (this.length === 0) {
            console.log('Error!');
            return this;
        }
        console.log(options);
        return this;
    }
    export var testBody = function() {
        jQuery('body').test({ 'HELLO': 'TEST' });
    }
}

问题

现在我在控制台中运行以下代码: tsc -m amd -t ES5 Test.ts -d

我收到此错误:Test.ts(17,19): error TS2339: Property 'test' does not exist on type 'JQuery'.

有什么解决办法吗?

【问题讨论】:

    标签: javascript jquery namespaces typescript extending


    【解决方案1】:

    这对我有用:

    /// <reference path="typings/jquery/jquery.d.ts" />
    
    interface JQuery {
        test(options: Object): JQuery;
    }
    
    namespace MyNameSpace {
        var $ = jQuery;
    
        $.fn.test = function(options: Object): JQuery {
            if (this.length === 0) {
                console.log('Error!');
                return this;
            }
            console.log(options);
            return this;
        };
        export var testBody = function() {
            jQuery('body').test({ 'HELLO': 'TEST' });
        }
    }
    

    编辑:第二个解决方案

    /// <reference path="typings/jquery/jquery.d.ts" />
    
    namespace MyNameSpace {
    
        interface JQueryX extends JQuery {
            test(options: Object): JQuery;
        }
    
        $.fn.test = function(options: Object): JQuery {
            if (this.length === 0) {
                console.log('Error!');
                return this;
            }
            console.log(options);
            return this;
        };
    
        export var testBody = function() {
            let a:JQueryX = <JQueryX>$('body');
            a.test({ 'HELLO': 'TEST' });
            // OR
            (<JQueryX>$('body')).test({ 'HELLO': 'TEST' });
        }
    }
    

    您可以通过重构使testBody 更好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-05
      • 2011-06-28
      • 1970-01-01
      • 2014-09-18
      • 1970-01-01
      • 2012-10-26
      • 1970-01-01
      • 2017-11-24
      相关资源
      最近更新 更多