TypeScript extend JQuery under Namespace

若如初见. 提交于 2020-01-01 11:39:11

问题


I'm trying to extend the default JQuery interface and the default object jQuery by a function in TypeScript

Code

/// <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' });
    }
}

The Problem

Now I'm running the following code in my console: tsc -m amd -t ES5 Test.ts -d

I'm getting this error: Test.ts(17,19): error TS2339: Property 'test' does not exist on type 'JQuery'.

Any solution for this?


回答1:


This works for me:

/// <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' });
    }
}

EDIT: 2nd solution

/// <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' });
    }
}

You can make the testBody nicer by some refactoring.



来源:https://stackoverflow.com/questions/33277521/typescript-extend-jquery-under-namespace

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!