TypeScript extend JQuery under Namespace

703
November 22, 2016, at 4:45 PM

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?

Answer 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.

Rent Charter Buses Company
READ ALSO
don&#39;t hide Lightbox if child is clicked

don't hide Lightbox if child is clicked

I have a Lightbox, and inside a centered child with content. The child also has a close button.

304
How to set cache: false in jQuery.get call

How to set cache: false in jQuery.get call

jQuery. get() is a shorthand for jQuery.

676
How can i validate file type using ajax in codeigniter

How can i validate file type using ajax in codeigniter

I am working on Codeigniter, i am facing one problem i have to show the user error message when he is uploading any other file type to server using ajax. I do not want to load view again to show the error message.

423
Update of select after adding data with ajax in codeigniter

Update of select after adding data with ajax in codeigniter

On my view i have select list like on picture and from plus button its available to add new one. After adding new one the list is not refreshing.

427